Thursday, July 29, 2010

ASP.NET - -Selection Sort

 Selection Sort

The selection sort works by selecting the smallest unsorted item remaining in the list, and then swapping it with the item in the next position to be filled.

This is a performance improvement over the bubble sort, but the Insertion Sort is over twice as fast as the Bubble Sort and is just as easy to implement as the selection sort. In short, there really isn't any reason to use the selection sort - use the Insertion Sort instead.

If you really want to use the selection sort for some reason, try to avoid sorting lists of more than a 1000 items with it or repetitively sorting lists of more than a couple hundred items.

Selection Sort Routine Code

// array of integers to hold values
private int[] a = new int[100];
// number of elements in array
private int x;
// Selection Sort Algorithm
public void sortArray()
int i, j;
int min, temp;
for( i = 0; i < x-1; i++ )
min = i;
for( j = i+1; j < x; j++ )
if( a[j] < a[min] )
min = j;
temp = a[i];
a[i] = a[min];
a[min] = temp;

No comments:

Post a Comment