算法導論——2.1-2選擇排序

題目:考慮排序存儲在數組A中的n個數:首先找出A中的最小元素並將其和A[1]中的元素交換。接着,次大值和A[2]交換。以此類推。


#include<iostream>

using namespace std;

int main()
{
	int a[100];
	int n, t = 0;
	cout << "input the size of array:" << endl;
	cin >> n;
	for (size_t i = 0; i < n; ++i)
		cin >> a[i];
	for (size_t i = 0; i < n; ++i)
	{
		int key = a[i];
		int temp = 0;
		for (size_t j = i; j < n; ++j)
		{
			if (a[j] < key)
			{
				key = a[j];
				t = j;
			}
		}
		a[t] = a[i];
		a[i] = key;
	}
	for (size_t i = 0; i < n; ++i)
		cout << a[i] << " ";
	cout << endl;
	return 0;
}

發佈了44 篇原創文章 · 獲贊 5 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章