C++ 选择排序、冒泡排序、插入排序

来源:互联网 发布:it资讯 编辑:程序博客网 时间:2024/06/08 13:55

//sort.h

#include "stdlib.h"#include "stdio.h"#include <iostream>template<typename T>class Sort { public://void SelectSort(T* array, int size);void SelectSort(T*arrayint size) {int temp = 0;for (int i = 0; i < size; i++){temp = i;for (int j = i + 1; j < size; j++) {//每一次排序确定的是最前面的一个数if (array[temp] > array[j]) {//记录一轮比较下来的最大值的地方,和出发的地方进行交换temp = j;}}if (temp != i) {Swap(array, temp, i);}}std::cout << "SelectSort:";for (int i = 0; i < size; i++){std::cout << array[i] << std::endl;}}//插入排序第一次前两个数进行排序// 第二次前三个数进行排序// 第三次前四个数进行排序//template<typename T>void Sort::InsertSort(T*arrayint size) {for (int i = 1; i < size; i++){for (int j = i; j>0; j--){if (array[j]<array[j - 1]) {Swap(array, j, j - 1);}}}std::cout << "InsertSort:";for (int i = 0; i < size; i++){std::cout << array[i] << std::endl;}}//冒泡排序第一次每两个进行排序,排到最后,那么最大的在最后// 第二次,除去最大的,把剩下的进行第一次那样的排序操作//template<typename T>void Sort::BubbleSort(T*arrayint size) {//每一次排序确定的是最后面的一个数 for (int i = 0; i < size; i++) {for (int j = 1; j < size - i; j++){if (array[j]<array[j - 1]) {//小一位大于大一位,那么交换位置Swap(array, j, j - 1);}}}std::cout << "InsertSort:";for (int i = 0; i < size; i++){std::cout << array[i] << std::endl;}}//template void InsertSort(T* array, int size);//template  void BubbleSort(T* array, int size); //template void Sort::Swap(T* array, int x, int y);void Sort::Swap(Tarrayint xint y){T temp = array[x];array[x] = array[y];array[y] = temp;} }; --------------------------------------------------------------------------------
#include "sort.h" void main() { int array[] = {1,10,4,2,11,20,14,23,12}; Sort<int> sort;sort.BubbleSort(array,9);sort.SelectSort(array,9);sort.InsertSort(array, 9);getchar(); }