题目:
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);
}
本文详细介绍了选择排序算法的实现原理和过程,包括其伪代码、循环不变式、时间复杂度分析及C++代码实现。选择排序通过多次遍历,将数组中的最小元素依次放置到正确的位置,实现对整个数组的排序。
18万+

被折叠的 条评论
为什么被折叠?



