Advertisement
sailorbob74133

DSA Maman 11 Q1

Mar 18th, 2013
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.50 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. void printA(int a[], int len) {
  5.     for (int i = 0; i != len; i++)
  6.         printf("%d ", a[i]);
  7.     printf("\n");
  8. }
  9.    
  10. void insSort(int A[], int len) {
  11.     int compares = 0;
  12.     int copies = 0;
  13.  
  14.     printA(A, len);
  15.     for (int j = 1; j != len; j++) {
  16.         int key = A[j];
  17.         copies++;
  18.         // Insert A[j] into the sorted sequence A[1 ... j - 1]
  19.         int i = j - 1;
  20.         for ( ; i != -1 && ++compares && A[i] > key; i--) {
  21.             A[i+1] = A[i];
  22.         //    printA(A, len);
  23.             copies++;
  24.         }
  25.         // printf("*** %d key compares\n", compares);
  26.         A[i+1] = key;
  27.         copies++;
  28.     }
  29.     printf("*** %d key compares\t", compares);
  30.     printf("*** %d element copies\n", copies);
  31.     printA(A, len);
  32.     printf("\n");
  33. }
  34.  
  35. int *build_arrayA(int n) {
  36.     int *a = malloc(sizeof(int)*n);
  37.     int i = 0;
  38.     for (int val = n/2; val < n+1; val++,i++)
  39.         a[i] = val;
  40.     for (int val = 1; val < n/2; val++, i++)
  41.         a[i] = val;
  42.  
  43.     return a;
  44. }
  45.  
  46. int *build_arrayB(int n) {
  47.     int *a = malloc(sizeof(int)*n);
  48.     int i = 0,j = 0;
  49.     int val = n/2;
  50.     a[i] = val;
  51.     while (1) {
  52.         a[++i] = val + ++j;
  53.         if (j == val) break;
  54.         a[++i] = val - j;
  55.     }
  56.     return a;
  57. }
  58.  
  59. int main(void) {
  60.     for (int i = 2; i != 14; i+=2) {
  61.         //int *a = build_arrayA(i);
  62.         int *a = build_arrayB(i);
  63.         insSort(a, i);
  64.         free(a);
  65.     }
  66.  
  67.     return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement