Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- void printA(int a[], int len) {
- for (int i = 0; i != len; i++)
- printf("%d ", a[i]);
- printf("\n");
- }
- void insSort(int A[], int len) {
- int compares = 0;
- int copies = 0;
- printA(A, len);
- for (int j = 1; j != len; j++) {
- int key = A[j];
- copies++;
- // Insert A[j] into the sorted sequence A[1 ... j - 1]
- int i = j - 1;
- for ( ; i != -1 && ++compares && A[i] > key; i--) {
- A[i+1] = A[i];
- // printA(A, len);
- copies++;
- }
- // printf("*** %d key compares\n", compares);
- A[i+1] = key;
- copies++;
- }
- printf("*** %d key compares\t", compares);
- printf("*** %d element copies\n", copies);
- printA(A, len);
- printf("\n");
- }
- int *build_arrayA(int n) {
- int *a = malloc(sizeof(int)*n);
- int i = 0;
- for (int val = n/2; val < n+1; val++,i++)
- a[i] = val;
- for (int val = 1; val < n/2; val++, i++)
- a[i] = val;
- return a;
- }
- int *build_arrayB(int n) {
- int *a = malloc(sizeof(int)*n);
- int i = 0,j = 0;
- int val = n/2;
- a[i] = val;
- while (1) {
- a[++i] = val + ++j;
- if (j == val) break;
- a[++i] = val - j;
- }
- return a;
- }
- int main(void) {
- for (int i = 2; i != 14; i+=2) {
- //int *a = build_arrayA(i);
- int *a = build_arrayB(i);
- insSort(a, i);
- free(a);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement