选择排序

一、原理:

     对于序列[0, ..., n-1],首先找出A中最小的元素并将其与A[0]交换。接着找出A中第二小的元素,即A[1, .., n-1]中的最小元素与A[1]交换,对A中的前n-1的元素按该方式继续...

二、代码:

 1 /*Sample Input:
 2   5
 3   -1 3 9 8 4
 4   
 5   Sample Output:
 6   -1 3 4 8 9
 7 */
 8 
 9 #include<bits/stdc++.h>
10 using namespace std;
11 
12 int main(int argc, char const *argv[])
13 {
14     int t;//输入序列大小 
15     while(cin >> t && t){
16         int arr[t];
17         for(int i = 0; i < t; i++)cin >> arr[i];
18         for(int i = 0; i < t-1; i++){
19             int index = i;
20             
21             for(int j = i; j < t; j++){//寻求最小值 
22                 if(arr[j] < arr[index]){
23                     index = j;
24                 }
25             }
26 
27             int tmp = arr[i];
28             arr[i] = arr[index];
29             arr[index] = tmp;
30         }
31 
32         for(int i = 0; i < t; i++)cout << arr[i] << ' ';
33         cout << endl;
34     }
35     return 0;
36 }

三、分析:

  因为每一次都需要对子序列进行遍历,所以其最好和最坏的情况的时间复杂度都是O(n^2)规模。

  //End

原文地址:https://www.cnblogs.com/Vincent-Bryan/p/5968625.html