多种排序法

计算机程序设计中有两个很经典的排序算法,他们分别是冒泡排序法和选择排序法。在编程的时候很多地方都会遇到排序,就像C/C++没有排序函数那样,那么就需要我们自己手动写排序算法。

[注意]

下面的例子都是用C++和Win32控制台程序写的!

冒泡排序法:

#include <iostream>
#include <time.h>

using namespace std;

template <class T>

int arraylen(T& array){
	return (sizeof(array) / sizeof(array[0]));
}

int main()
{
	int box[10];
	int temp;

	srand((unsigned)time(NULL));

	for(int i = 0; i < arraylen(box); i++){
		box[i] = rand() % 100;
		cout << box[i] << "\t";
	}

	cout << endl;

	for(int i = 1; i < arraylen(box); i++){
		for(int j = 0; j < arraylen(box) - i; j++){
			if(box[j] > box[j + 1]){
				temp = box[j];
				box[j] = box[j + 1];
				box[j + 1] = temp;
			}
		}
	}

	for(int i = 0; i < arraylen(box); i++){
		cout << box[i] << "\t";
	}

	cout << endl;
	system("pause");

	return 0;
}

选择排序法:

#include <iostream>
#include <time.h>

using namespace std;

template <class T>

int arraylen(T& array){
	return (sizeof(array) / sizeof(array[0]));
}

int main()
{
	int box[10];
	int temp, index;

	srand((unsigned)time(NULL));

	for(int i = 0; i < arraylen(box); i++){
		box[i] = rand() % 100;
		cout << box[i] << "\t";
	}

	cout << endl;

	for(int i = 0; i < arraylen(box) - 1; i++){
		index = i;
		for(int j = i + 1; j < arraylen(box); j++){
			if(box[j] < box[index]){
				index = j;
			}
		}

		if(index != i){
			temp = box[i];
			box[i] = box[index];
			box[index] = temp;
		}
	}

	for(int i = 0; i < arraylen(box); i++){
		cout << box[i] << "\t";
	}

	cout << endl;
	system("pause");

	return 0;
}

标签:计算机, 程序, 设计, 常用, 算法, 排序

该文章由 Shiqi 原创并发布在 被遗忘的曙光 技术博客

转载请标明来源:https://blog.fdawn.com/CPP/9.html

已有 2 条评论

  1. 进存软件

    非常不错的文章,过来看看学习,希望博主分享更多好的文章。

    1. Nollie

      That's really thikinng of the highest sort.

添加新评论