1. 程式人生 > >1Insert Sort

1Insert Sort

#include <stdio.h>
void PrintArray(int *a, int len);
int  InsertSort(int *a, int len);
int  ShellSort(int *a, int len, int d);
#define LENGTH 10
int array[LENGTH] = {4, 1, 5, 7, 9, 8, 6, 0, 3, 2};
//int array[LENGTH] = {2, 3, 4, 1, 9, 8, 6, 0, 3, 2};
void main()
{
    PrintArray(array, LENGTH);
    
//InsertSort(array, LENGTH); /* ShellSort(array, LENGTH, 5); ShellSort(array, LENGTH, 2); ShellSort(array, LENGTH, 1); */ BinaryInsertSort(array, LENGTH); PrintArray(array, LENGTH); } void PrintArray(int *a, int len) { printf("\n"); int i; for(i = 0; i < len; i++) printf(
"%d ", a[i]); //printf("a[%d] = %d\n", i, a[i]); printf("\n"); } int InsertSort(int *a, int len) { int i = 0; for(i = 0; i < len; i++) { int j = i-1; int temp = a[i]; while((j >= 0)&&(a[j] > temp)) { a[j+1] = a[j]; j
--; } a[j+1] = temp; } } int ShellSort(int *a, int len, int d) { int i = 0; for(i = 0; i < len; i++) { int j = i-d; int temp = a[i]; printf("i=%d j=%d temp=%d\n", i, j, temp); while((j >= 0)&&(j < len)&&((j+d) >= 0)&&((j+d) < len)&&(a[j] > temp)) { printf("hit a[%d]=%d temp=%d\n", j, a[j], temp); a[j+d] = a[j]; j-= d; } a[j+d] = temp; } } int BinaryInsertSort(int *a, int len) { int i = 0; for(i = 0; i < len; i++) { int temp = a[i]; int low = 0, high = i-1, mid; while(high >= low) { mid = (low + high)/2; if(a[mid] > temp) { high = mid - 1; } else { low = mid + 1; } } //a[high + 1] = temp; printf("i=%d h=%d l=%d\n", i, high, low); int j = i - 1; while((j >= 0)&&(j > high)) { a[j+1] = a[j]; j--; } a[j+1] = temp; PrintArray(a, LENGTH); } }