Shell排序

来源:互联网 发布:农村淘宝村小二招募 编辑:程序博客网 时间:2024/06/08 10:24
步骤:
 1、将n个元素的数组分成n/2个数字序列,第一个数据和第n/2+1个数据为一对
 2、一次循环每个序列对排序好
 3、然后在变成n/4个序列,再次排序
 4、不断重复,直到序列最后变为1,及完成整个序列


// ShellSort.cpp : Defines the entry point for the console application.

//#include "stdafx.h"#include<IOSTREAM>#include<CSTDIO>#include<CSTDLIB>#include<CSTRING>#include<CTIME>using namespace std;#define  SIZE 10void ShellSort(int *a, int len){int i,j,h;int r,temp;int x = 0;for (r = len/2; r >= 1; r /= 2)// 分组{for (i=r; i < len; i++)// 插入排序{temp = a[i];j = i - r;while(j >= 0 && temp < a[j]){a[j+r] = a[j];j -= r;}a[j+r] = temp;}x++;cout<<"step "<<x <<" "<< r <<" "<< i <<" "<< j <<" sort"<<endl;for (h = 0; h < len; h++) {cout<<a[h]<<" ";}cout<<endl;}}int main(int argc, char* argv[]){int array[SIZE], i;srand(time(NULL));for (i = 0;i < SIZE; i++){array[i] = rand() / 1000 + 100;}cout<<"before sort -------------"<<endl;for (i = 0; i < SIZE; i++){cout<<array[i]<<" ";}cout<<endl;ShellSort(array, SIZE);cout<<"Sort: ------------------"<<endl;for (i = 0; i < SIZE; i++){cout<<array[i]<<" ";}cout<<endl;getchar();return 0;}before sort -------------118 123 114 102 105 128 124 130 104 128step 1 5 10 4 sort118 123 114 102 105 128 124 130 104 128step 2 2 10 5 sort104 102 105 123 114 128 118 128 124 130step 3 1 10 8 sort102 104 105 114 118 123 124 128 128 130Sort: ------------------102 104 105 114 118 123 124 128 128 130


原创粉丝点击