选择排序(Selection Sort)

C++自学精简教程 目录(必读)


选择排序
每次从未排序子数组中选中最小的元素,与已排序子数组的末尾元素交换。

输入数据


42 20 17 13 28 14 23 15


执行过程

选择排序(Selection Sort)_第1张图片

完整代码

#include 
#include 
#include 
using namespace std;

void print_array(const char* msg, int* arr, int n)
{
	cout << msg << " ";
	for (int i = 0; i < n; i++)
	{
		cout << arr[i] << " ";
	}
	cout << endl;
}
//swap two number
void Swap(int& a, int& b)
{
	int tmp = a; a = b; b = tmp;
}

//select the min element, return the index of the min element
int SelectMin(int* arr, int start, int total)
{
	int min = arr[start];
	int index = start;
	for (int i = start; i < total; ++i)
	{
		if (min > arr[i])
		{
			//(1) your code 筛选出最小值元素对应的下标


		}
	}
	return index;
}

void SelectSort(int* arr, int n)
{
	for (int i = 0; i < n; i++) { //  i != min  =>  swap(arr[i], arr[min])
		int index = SelectMin(arr, i, n);
		if (index != i)
		{
			//(2) your code 将 arr[i] 和 arr[index] 交换
			
		}
		print_array("one trip", arr, n);
	}
}

void test(vector arr)
{
    //输出原始序列
	print_array("original array:", arr.data(), arr.size());
	//执行排序,并输出排序过程
	SelectSort(arr.data(), arr.size());
	//输出排序后的列表
	print_array("after sorted:",arr.data(), arr.size());
	cout << endl;
}

int main()
{
	test({ 1 });
	test({ 1 , 2 });
	test({ 2 , 1 });
	test( { 2 , 2 });
	test({ 42, 20, 17, 13, 28, 14, 23, 15 });
	test({ 1, 8, 3, 6, 5, 4, 7, 2 , 9 });
	test( { 8, 8, 6, 6, 7, 5, 5, 7, 9 , 9});
	return 0;
}

执行结果

original array: 1
one trip 1
after sorted: 1

original array: 1 2
one trip 1 2
one trip 1 2
after sorted: 1 2

original array: 2 1
one trip 1 2
one trip 1 2
after sorted: 1 2

original array: 2 2
one trip 2 2
one trip 2 2
after sorted: 2 2

original array: 42 20 17 13 28 14 23 15
one trip 13 20 17 42 28 14 23 15
one trip 13 14 17 42 28 20 23 15
one trip 13 14 15 42 28 20 23 17
one trip 13 14 15 17 28 20 23 42
one trip 13 14 15 17 20 28 23 42
one trip 13 14 15 17 20 23 28 42
one trip 13 14 15 17 20 23 28 42
one trip 13 14 15 17 20 23 28 42
after sorted: 13 14 15 17 20 23 28 42

original array: 1 8 3 6 5 4 7 2 9
one trip 1 8 3 6 5 4 7 2 9
one trip 1 2 3 6 5 4 7 8 9
one trip 1 2 3 6 5 4 7 8 9
one trip 1 2 3 4 5 6 7 8 9
one trip 1 2 3 4 5 6 7 8 9
one trip 1 2 3 4 5 6 7 8 9
one trip 1 2 3 4 5 6 7 8 9
one trip 1 2 3 4 5 6 7 8 9
one trip 1 2 3 4 5 6 7 8 9
after sorted: 1 2 3 4 5 6 7 8 9

original array: 8 8 6 6 7 5 5 7 9 9
one trip 5 8 6 6 7 8 5 7 9 9
one trip 5 5 6 6 7 8 8 7 9 9
one trip 5 5 6 6 7 8 8 7 9 9
one trip 5 5 6 6 7 8 8 7 9 9
one trip 5 5 6 6 7 8 8 7 9 9
one trip 5 5 6 6 7 7 8 8 9 9
one trip 5 5 6 6 7 7 8 8 9 9
one trip 5 5 6 6 7 7 8 8 9 9
one trip 5 5 6 6 7 7 8 8 9 9
one trip 5 5 6 6 7 7 8 8 9 9
after sorted: 5 5 6 6 7 7 8 8 9 9

你可能感兴趣的:(C++数据结构与算法实现,算法,c++,数据结构,开发语言,排序算法)