CS3343/3341 Analysis of Algorithms Spring 2012 |
Recursive
Selection Sort ANSWERS |
[Below is are programs answering the questions. The Java program on the left is a direct and straightforward answer. The C program on the right does all the same things, but differs from the requirements in various minor ways. Notice that the program on the right took almost exactly 100 times as long to sort 10 times as many number, just as we would expect from a Θ(n2) algorithm.] The programs below create an array A of 15 random doubles. They use a recursive function max to find the largest element in this array.
For this question, you are asked to write a recursive selection sort function by making additions and changes to either the Java or the C progam below (or both) in the following steps:Recursive Selection Sort | |
---|---|
Java | C |
public class SelectionSort { final static int N = 15; public static void main(String[] args) { double[] A = new double[N]; // random numbers init(A, N); // rand #s for A[0], ..., A[N-1] printit(A, N); // print them System.out.println("Sorted:"); selectionSort(A, N); printit(A, N); // print them } static int maxind(double[] A, int n) { int maxi; if (n == 1) return 0; maxi = maxind(A, n-1); if (A[n-1] > A[maxi]) return n-1; return maxi; } static void init(double[] A, int n) { int i; for (i = 0; i < n; i++) // 0 < A[i] < 1, uniformly distributed A[i] = Math.random(); } static void interchange(double[] A, int i, int j) { double temp = A[i]; A[i] = A[j]; A[j] = temp; } static void selectionSort(double[] A, int n) { if (n > 1) { int maxi = maxind(A, n); interchange(A, maxi, n-1); selectionSort(A, n-1); } } static void printit(double[] A, int n) { for (int i = 0; i < n; i++) System.out.println("A[" + i + "]: " + A[i]); } } | #include <stdlib.h> #include <time.h> #define M 10000 void inita(void); void check_sorted(void); void sort_select(int n); int maxind(int); void swap(double *, double *); double a[M]; void main(void) { int starttime, stoptime; /* elapsed time */ int startclock, stopclock; /* CPU time */ srand48((long)time(NULL)); inita(); starttime = time(NULL); startclock = clock(); sort_select(M-1); stoptime = time(NULL); stopclock = clock(); printf("Sorting %i numbers\n", M); printf("Elapsed time: %ld seconds\n", stoptime - starttime); printf("CPU time: %.3f seconds\n", (double)(stopclock - startclock)/1000000.0); check_sorted(); } void sort_select(int n) { int maxi; if (n > 0) { maxi = maxind(n); swap(&a[maxi], &a[n]); sort_select(n-1); } } int maxind(int m) { int maxi; if (m == 0) return m; maxi = maxind(m-1); if (a[m] > a[maxi]) return m; return maxi; } void swap(double *x, double *y) { double z = *x; *x = *y; *y = z; } void inita(void) { int i; for (i = 0; i < M; i++) a[i] = drand48(); } void check_sorted(void) { int sorted = 1; int i; for (i = 0; i < M-1; i++) if (a[i] > a[i+1]) sorted = 0; if(sorted) printf("Array sorted\n"); else printf("*** Array NOT sorted\n"); } |