冒泡排序 ,选择排序,插入排序
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<random>
#include<time.h>
#include<sys/timeb.h>
using namespace std;
#define MAX 10long getSystemTime()
{struct timeb tb;ftime(&tb);return tb.time * 1000 + tb.millitm; //毫秒
}void printArr(int arr[], int length)
{for (int i = 0; i < length; i++){printf("%d ", arr[i]);}printf("\n");
}void Swapp(int *a, int *b)
{//int temp;int temp = *a;*a = *b;*b = temp;
}//从小到大排序
void bubbleSort1(int arr[], int length)
{for (int i = 0; i < length; i++) //从前到后排序{for (int j = 0; j < length - i - 1; j++){if (arr[j] > arr[j + 1]){Swapp(&arr[j], &arr[j + 1]);}}}
}
//从小到大排序
void bubbleSort2(int arr[], int length)
{for (int i = 0; i < length; i++) //从后往前排序{for (int j = length - 1; j > i; j--){if (arr[j] < arr[j - 1]){Swapp(&arr[j], &arr[j - 1]);}}}
}//冒泡排序2改进版
int flag = 0; //0表示没有排序好
void BubbleSort(int arr[], int length)
{for (int i = 0; i < length&&flag==0; i++) //从后往前排序{flag = 1; //认为已经排序好for (int j = length - 1; j > i; j--){if (arr[j] < arr[j - 1]){flag = 0;Swapp(&arr[j], &arr[j - 1]);}}}
}//从小到大排序
void selectSortme(int arr[], int length)
{ for (int i = 0; i < length; i++) //从前到后排序{//for (int j = i+1; j < length-i-1; j++)//这里j初始值在一直增加,所以长度为lengthfor (int j = i + 1; j < length; j++){if (arr[j] <= arr[i]){Swapp(&arr[i], &arr[j]);}}printf("");printArr(arr, MAX);}
}
void selectSort(int arr[], int length)
{for (int i = 0; i < length; i++) //从前到后排序{int min = i;for (int j = i + 1; j < length; j++){if (arr[j] < arr[min]){min = j;}}//Swapp(&arr[min], &arr[i]); 交换次数多if (min != i) //交换次数少{Swapp(&arr[min], &arr[i]);}}
}void insertSort(int arr[], int length) //如何定义新数组???
{int j;for (int i = 1; i < length; i++) //从第二个数开始是无序队列。第一个数为有序队列{if (arr[i]<arr[i-1]){int temp = arr[i]; //将满足条件的元素缓冲到temp中for (j = i-1; j >=0 && temp < arr[j]; j--) //将前面的移到后面,方便插入{arr[j + 1] = arr[j];}arr[j + 1] = temp; //填补坑}}
}int main()
{int arr[MAX];srand((unsigned int)time(NULL)); //种子for (int i = 0; i < MAX; i++){arr[i] = rand() % MAX;}printf("未排序数组为:");printArr(arr, MAX);long t_start = getSystemTime();insertSort(arr, MAX);long t_end = getSystemTime();printf("冒泡排序后数组为:");printArr(arr, MAX);//printf("冒泡排序%d个元素,所需时间:%1d\n", MAX, t_end - t_start);system("pause");return 0;
}
插入排序过程: