Thursday, February 10, 2011

Selection Sort

is a sorting algoritm in which every item will be emplimented every time like insertion sort. Instead of inserting the first item of the unsorted list to the sorted list, the algorithm will just select the smallest value in the unsorted list and add it to the last element of the sorted list.

Algorithm:
The list will be devided imaginarilly into sorted and unsorted list. The algorithm will select the first element of the sorted list, which is, the smallest value in the group. And in every step, the algorithm will find and select the smallest item in the unsorted list and adds it to the end of the sorted list.

Pseudocode(C++):

void selectionSort(int arr[], int n) {
int i, j, minIndex, tmp;
for (i = 0; i < n - 1; i++) {
minIndex = i;
for (j = i + 1; j < n; j++)
if (arr[j] < arr[minIndex])
minIndex = j;
if (minIndex != i) {
tmp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = tmp;
}
}
}

Source:
http://en.wikipedia.org/wiki/Selectionsort
http://www.algolist.net/Algorithms/Sorting/Selection_sort

No comments:

Post a Comment