You are viewing a single comment's thread. Return to all comments →
Feel free to let me know if there's any issue in this C code.
#define min(x, y) (((x) < (y)) ? (x) : (y)) int comp(const void * a, const void * b){ return *(int*)a-*(int*)b; } int no_of_swaps(int *arr,int arr_count){ int *a = (int*)malloc(arr_count*sizeof(int)); int* sort; int i,c=0; for(i=0;i<arr_count;i++){ a[i] = arr[i]; } qsort(a,arr_count,sizeof(int),comp); for(i=0;i<arr_count;i++){ if(arr[i] != a[i]){ c +=1; int j = i+1; while(arr[j] != a[i]){ j++; } int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } free(a); return c; } int lilysHomework(int arr_count, int* arr) { int *arr_copy = (int*)malloc(arr_count*sizeof(int)); memcpy(arr_copy, arr, arr_count*sizeof(int)); int normal_order, reverse_order; normal_order = no_of_swaps(arr_copy,arr_count); int* reversed_arr = (int*)malloc(arr_count*sizeof(int)); for (int i = 0; i < arr_count; i++) { reversed_arr[i] = arr[arr_count - i - 1]; } reverse_order = no_of_swaps(reversed_arr,arr_count); return min(normal_order,reverse_order); }
Lily's Homework
You are viewing a single comment's thread. Return to all comments →
Feel free to let me know if there's any issue in this C code.