選擇排序--C++版

選擇排序 (比冒泡排序快一點,冒泡排序慢在有很多交換)
從當前未排序的整數中找一個最小的整數,將它放在已排序的整數列表的最後。
要點:選擇排序選最小的,往左邊選。
想像:一條毛巾
冒泡排序 與 選擇排序

#include<iostream>
using namespace std;
void SelectSort(int* a, const int n);  //聲明一個函數
int main()
{
	int x[] = { 1,3,5,7,9,0,2,4,6,8 };  //定義一個數組。
	SelectSort(x, 10);  //選擇排序,10個數

	for (int k = 0; k < 10; k++)
		cout << x[k] << endl;
	return 0;
}
void SelectSort(int* list , const int n)   //函數的定義
{
	for (int i = 0; i < n; i++)     //用來定義掃描的次數    10個數就掃描10遍   n可以改成n-1
	{
		int min = i; //min就是毛巾,毛巾是數組的下標
		for (int j = i + 1; j < n; j++)      //
		{
			if (list[j] < list[min])
				min = j;       //改變毛巾的位置
		}
		swap(list[i], list[min]);   //一遍掃描完後進行一次交換
	}
}


select不是selcet

p敲成o
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章