您的位置:首页 > 其它

Seletion Sort

2015-10-06 05:13 267 查看
referrence: GeeksforGeeks

The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array.

1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.

In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.



public static void SelectionSort ( int [ ] num )
{
int i, j, min, minIndex;
for ( i = 0; i < num.length; i++ )
{
min = num[i];   //initialize min
for(j = i; j < num.length; j ++)   //inside loop
{
if( num[j] < min) {
min = num[j];
minIndex = j;
}
}
//swap min and num[i];
num[j] = num[i];
num[i] = min;
}
}


Time comlexity O(n^2), space cost O(1), and it is in-place sorting.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: