Monday, 20 December 2010

Algorithm for selection sort

Description:


This is the simplest method of sorting. In this method, to sort the data in ascending order, the 0th element is compared with all other eements. If the 0th element is found to be greater than the compared element then they are interchanged.

Algorithm:

1) Start 
2) Initiliaze the variables I,j,temp and arr[] 
3) Read the loop and check the condition. If the condition is true print the array elements and increment the I value. Else goto step 4 
4) Read the loop and check the condition. If the condition true then goto next loop. 
5) Read the loop and check the condition. If the condition true then goto if condition 
6) If the condition if(arr[i]>arr[j]) is true then do the following steps 
i) temp=arr[i] 
ii) arr[i]=arr[j] 
iii) arr[j]=temp 
7) increment the j value 
8) perform the loop operation for the displaying the sorted elements. 
9) print the sorted elements 
10) stop 


More Explanation:
In a selection sort, the algorithm divides a list into two sub-lists – one sorted and one unsorted. An imaginary barrier separates the two lists.
The algorithm finds the smallest value in the unsorted list and swaps it with the first value in the unsorted list. Then, the barrier moves to include that item in sorted list.

With each sort pass, we increase the size of the sorted list by one (and decrease the size of the unsorted list by one).
In a list with n elements, we need n-1 sort passes to order the list.







Data structures using Java

No comments:

Post a Comment