#include <stdio.h> #define N 10
void print_data(int[],int); void asc_insert(int[],int,int); void desc_insert(int[],int,int); int main(int argc, int *argv[]) { //int a[N] = {3,6,9,13,16,19,20,36,50}; // asc
int a[N] = {50,36,20,19,16,13,9,6,3}; //desc
int ipt_value,i; int key = -1,n = N; int cur_sort = a[0] < a[1] ? 1 : 0; //1 is asc,0 is desc
print_data(a,N-1); printf("\nplease input a number:"); scanf("%d",&ipt_value); if (cur_sort) { asc_insert(a,N,ipt_value); print_data(a,N); } else { desc_insert(a,N,ipt_value); print_data(a,N); } system("pause"); return 0; }
void print_data(int a[],int n) { int i; for (i = 0; i < n; i++) { printf("%d ",a[i]); } }
void asc_insert(int a[],int n,int key) { int i,j; int key_point = -1; for (i = 0; i < n - 1 ;i++) { if (key > a[i]) { continue; } else { key_point = i; break; } } if (-1 == key_point) { a[n-1] = key; } else { j = n - 1; for (i = n - 2; i >= 0 ; i--) { if (key_point != i) { a[j--] =a[i]; } else { a[j--] = a[i]; a[j] = key; break; } } } }
void desc_insert(int a[],int n,int key) { int i,j; int key_point = -1; for (i = 0; i < n - 1; i++) { if (key < a[i]) { continue; } else { key_point = i; break; } } if (-1 == key_point) { a[n-1] = key; } else { j = n - 1; for (i = n - 2; i >= 0; i--) { if (i != key_point) { a[j--] = a[i]; } else { a[j--] = a[i]; a[j] = key; break; } } } }
|