C++ 插入排序,冒泡排序和选择排序
刚试着重写/温习了3个最简单的排序算法。
插入排序:依次将右边未排序的元素插入到左边已排序序列的合适位置。
时间复杂度:O(n^2)
float* sort_insertion(float a[], int len_a){/*插入排序 类似我们排序扑克牌*/for(int i=1; i < len_a; i++){float to_insert = a[i];// 索引0到 i-1 已排好序int j;for(j = i-1; a[j] > to_insert and j >=0 ; j--)a[j+1] = a[j];//大的往后退一位a[j+1] = to_insert;//a[j] > to_insert 不成立时 j+1的值即是待插入的位置}return a;}
冒泡排序和选择排序大学都学过,不再赘述。
冒泡排序:
时间复杂度:O(n^2)
float* sort_bubble(float a[], int len_a){/*冒泡排序 依次比较相邻的两个元素,如果顺序错误就将它们的位置交换 */float temp;for(int i=0; i < len_a-1; i++){for(int j =0 ;j<len_a-1-i; j++){if (a[j] > a[j+1]){temp = a[j];a[j] = a [j+1];a[j+1] = temp;}}}return a;}
选择排序:
时间复杂度:O(n^2)
float* sort_selection(float a[], int len_a){/*选择排序 依次将左边未排序序列中的最大元素,存放到右边已排序序列的左端 */int j;float temp;for(int i= len_a-1; i >= 0; i--){//未排序序列:a[0]到a[i]//找到未排序序列的最大元素的位置int maxIndex = 0;for(j=1; j <= i; j++){if (a[j] > a[maxIndex])maxIndex = j;}//交换temp = a[i];a[i] = a[maxIndex];a[maxIndex] = temp;}return a;}
随机数组生成部分的代码如下:
using namespace std;float* sort_insertion(float a[], int len_a);float* sort_bubble(float a[], int len_a);float* sort_selection(float a[], int len_a);int main(){const int len_b =100;float b[len_b];//int len_b = sizeof(b)/sizeof(b[0]);//求数组长度srand(time(NULL)); //srand()设置随机种子seed, seed 随时间变化for (int i=0; i<len_b; i++){b[i] = rand()%101 -50.0f;//随机数 -50 到 50//cout <<b[i]<<endl;}sort_bubble(b,len_b);//cout<<endl;for (int i=0;i<len_b;i++)cout<<b[i]<<endl;return 0;}
