Selection Sort In Java
Introduction
In
this example we are going to sort the values of an array using selection
sort.
In
selection sorting algorithm, find the minimum value in the array then swap it
first position. In next step leave the first value and find the minimum value
within remaining values. Then swap it with the value of minimum index position.
Sort the remaining values by using same steps. Selection sort is
probably the most intuitive sorting algorithm to invent.
The complexity of selection sort algorithm is in worst-case, average-case, and best-case run-time of Θ(n2), assuming that comparisons can be done in constant time.
Code description:
The complexity of selection sort algorithm is in worst-case, average-case, and best-case run-time of Θ(n2), assuming that comparisons can be done in constant time.
Code description:
In
selection sort algorithm to find the minimum value in the array. First assign
minimum index in key (index_of_min=x). Then find the minimum value and assign
the index of minimum value in key (index_of_min=y). Then swap the minimum
value with the value of minimum index.
At next iteration leave the value of minimum index position and sort the remaining values by following same steps.
Working of the selection sort :
At next iteration leave the value of minimum index position and sort the remaining values by following same steps.
Working of the selection sort :
Say
we have an array unsorted A[0],A[1],A[2]................ A[n-1] and A[n] as
input. Then the following steps are followed by selection sort algorithm to
sort the values of an array . (Say we have a key index_of_min that indicate the
position of minimum value)
1.Initaily varaible index_of_min=0;
2.Find the minimum value in the unsorted array.
3.Assign the index of the minimum value into index_of_min variable.
4.Swap minimum value to first position.
5.Sort the remaining values of array (excluding the first value).
1.Initaily varaible index_of_min=0;
2.Find the minimum value in the unsorted array.
3.Assign the index of the minimum value into index_of_min variable.
4.Swap minimum value to first position.
5.Sort the remaining values of array (excluding the first value).
class SelectionSorting{
public static void main(String arg[]){
int a[]={3,30,4,12,1,2,34,22,4,3,5,8};
System.out.println("\n\nInput values:");
for(int i=0;i<a.length;i++){
System.out.print(" "+a[i]);
}
for (int i = 0; i < a.length; i++){
int min = i;
int j;
/*
* Find the smallest element in the unsorted list
*/
for (j = i + 1; j < a.length; j++) {
if (a[j] < a[min]){
min = j;
}
}
/*
* Swap the smallest unsorted element into the end of the sorted list.
*/
int T = a[min];
a[min] = a[i];
a[i] = T;
}
System.out.println("\n\n\nSorted values:");
for(int i=0;i<a.length;i++)
{
System.out.print(" "+a[i]);
}
}
}
No comments:
Post a Comment