C++排序算法

1.冒泡排序

#include <cstdio>
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

void BubbleSort(vector<int> &arr, int len)
{
	int temp = {0};
	for (int i = 0; i < len - 1; ++i)
	{
		for (int j = 0; j < len - 1 - i; ++j)
		{
			if (arr[j] > arr[j + 1])
			{
				temp = arr[j + 1];
				arr[j + 1] = arr[j];
				arr[j] = temp;
			}
		}
	}
}
int main() {
	vector <int> B;
	cout << "請輸入3個數字!" << endl;
	int temp;
	for (int i = 0; i < 3; i++) {
		cin >> temp;
		B.push_back(temp);
	}
	int l = B.size();
	BubbleSort(B, l);
	vector<int>::iterator it;
	for (it = B.begin(); it != B.end(); it++)
		cout << *it << endl;
	system("pause");
	return 0;
}

2.選擇排序

void selectSort(vector <int> &a, int len)
{

	int minindex, temp;
	for (int i = 0; i < len - 1; i++)
	{
		minindex = i;
		for (int j = i + 1; j < len; j++)
		{
			if (a[j] < a[minindex])
				minindex = j;

		}
		temp = a[i];
		a[i] = a[minindex];
		a[minindex] = temp;
	}
}

3.插入排序

 

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