• 排序


    选择法

    基本思想。

    每一趟 (比如第 i 趟,i = 0, 1, …,n-2)在后面 n-i个待排的数据元素中选出keyword

    最小的元素, 作为有序元素序列的第 i 个元素。

    排序过程

      首先通过n-1次keyword比較,从n个记录中找出keyword最小的记录,将它与第一个记录交换;

      再通过n-2次比較,从剩余的n-1个记录中找出keyword次小的记录,将它与第二个记录交换;

      反复上述操作,共进行n-1趟排序后,排序结束。

    时间复杂度O(n^2)



    代码:

    #include <iostream>
    #include <cstdio>
    #include <ctime>
    #include <iomanip>
    using namespace std;
    
    int arr[10000];
    
    void mySwap(int &a, int &b)
    {
    	int t = a;
    	a = b;
    	b = t;
    }
    
    
    void selectSort(int *a, int len)
    {
    	for (int i = 0; i < len; i++) {
    		int k = i; // 记录最小的位置
    		for (int j = i + 1; j < len; j++) {
    			if (a[j] < a[k]) {
    				k = j;
    			}
    		}
    		if (k != i) {
    			mySwap(a[i], a[k]);
    		}
    	}
    }
    
    void printArray(int *a, int len)
    {
    	for (int i = 0; i < len; i++) {
    		if (i != 0 && i % 10 == 0) {
    			cout << endl;
    		}
    		cout << setw(3) << a[i] << ' ';
    	}
    	cout << endl;
    }
    
    int main()
    {
    	srand(time(0));
    	cout << "Please input length of array: ";
    	int len;
    	cin >> len;
    	for (int i = 0; i < len; i++) {
    		arr[i] = rand() % 100;
    	}
    	cout << "Before sorting:
    ";
    	printArray(arr, len);
    	selectSort(arr, len);
    	cout << "After sorting:
    ";
    	printArray(arr, len);
    	
    	return 0;
    }
    
    /*
    Please input length of array: 20
    Before sorting:
    3  28  35  97  87   7  33  60  84  47
    18  71  94  68  54  94  30   8  95  31
    After sorting:
    3   7   8  18  28  30  31  33  35  47
    54  60  68  71  84  87  94  94  95  97
    */

  • 相关阅读:
    iOS 快语句(block)浅析
    iOS中控制器的创建
    iOS中的截屏
    iOS&UITextView中的placeholder属性
    iOS归档,解档
    iOS内存警告浅析
    scrollWidth,clientWidth,offsetWidth的区别
    css3学习笔记
    页面重构的常用规范
    页面重构的职业定位
  • 原文地址:https://www.cnblogs.com/yjbjingcha/p/7047263.html
Copyright © 2020-2023  润新知