In: Computer Science
Q: Let’s say you have an unordered list of numbers and you wanted to put them in order from lowest to highest value. How would you do that? You’re probably thinking that you would just look at all the numbers, find the lowest number and put it at the beginning of your list. Then you would find the next largest number and put it in the second spot in the list, and so on until you’ve ordered the entire list of numbers. It’s simple, basic, and not very exciting. Now, let’s say that instead of ordering the list yourself, you decide it’s a better idea to write a computer program to order the list for you. Now you don’t have to deal with moving the numbers around, you just need to tell your program how to move the numbers, and then let the program handle any list you give it.Identify all possible ways of telling your program how to move the numbers, where each way provides the required result.
(Note: The program code is preferred to be in Java)
The solution to the above problem is:-
I have sorted the list by selecting the smallest number and then swapping them with the current loop variable index value.
i.e, if the smallest value is in the 3rd index and my current loop value index value is 1 then swapping is used to replace the smallest value. i.e, the 3rd index contains the value of the 1st index.
This is similar to the selection sort, where we will find the smallest numbers and order the list.
code for the above problem is:-
import java.util.*;
import java.lang.*;
class Selection
{
public static void main(String args[])
{
Scanner sc = new
Scanner(System.in); // for taking input.
int n;
System.out.println("Ente the size
of the array: ");
n=sc.nextInt(); //taking the size
of the array from the user.
int arr[] = new int[n]; // creating
an array with the size taken from the user.
int i;
System.out.println("Enter the array
elements:");
for(i=0;i<n;i++)
{
arr[i]=sc.nextInt(); // creating an array with elements taken from
the user.
}
System.out.print("Before arraing
array elements are: ");
for(i=0;i<n;i++)
{
System.out.print(arr[i]+" "); //printing the elements.
}
for(i=0;i<n;i++)
{
int index=i; //
to find the index value of the minimum number.
for(int
j=i+1;j<n;j++)
{
if(arr[j]<arr[index])
{
index=j; // finding the
minimum value's index .
}
}
int temp=arr[i];
// swapping the minimum number with the current element in the
array.
arr[i]=arr[index]; // swap arr[min] with arr[i] so that min number
will be in the starting of the loop.
arr[index]=temp;
}
System.out.print("\nElements after
arranging are: "); // after sorting printing the elements.
for (i=0;i<n;i++)
{
System.out.print(arr[i]+" ");
}
System.out.println();
}
}
Screenshots of the code:-
Output for the above code is:-