题目:
Consider sorting n numbers in an array A by first finding the smallest element of A and exchanging it with the element in A[1]. Then find the second smallest element of A, and exchange it with A[2]. Continue in this manner for the first n−1 elements of A. Write pseudocode for this algorithm, which is known as selection sort. What loop invariants does this algorithm maintain? Why does it need to run for only the first n−1 elements, rather than for all n elements? Give the best-case and the worst-case running times of selection sort in Θ-notation.
伪代码:
SELECTION-SORT(A):
for i = 1 to A.length - 1
min = i
for j = i + 1 to A.length
if A[j] < A[min]
min = j
temp = A[i]
A[i] = A[min]
A[min] = temp
循环不变式
在外部for循环的每次迭代开始时, A [ 1 … i – 1 ]包含数组中最小的i- 1元素,按非递减顺序排序。
在内部for循环的每次迭代开始时, A [min]是A[i…j – 1]中最小的数;
时间复杂度
Θ(n2) .
代码:
#include <iostream>
#include <vector>
#include <ctime>
using namespace std;
void search_sort(int *a){
int i;
for(i = 1;i <= 10;i++)
{
int min = i;
for(int j = i+1;j < 10;j++)
{
if(a[j] <a[min])
{
min = j;
}
}
int tmp;
tmp = a[i] ;
a[i] = a[min];
a[min] = tmp;
}
for(int i = 0;i<10;i++)
{
cout<<a[i]<<endl;
}
cout<<endl;
}
int main()
{
int a[10]={1,2,15,9,10,2,4,7,4,9};
for(int i = 0;i<10;i++)
{
cout<<a[i] <<endl;
}
search_sort(a);
}