0% found this document useful (0 votes)
65 views4 pages

hw5 2

1. The document describes a Java program that compares the performance of the merge sort and quick sort algorithms by timing how long each takes to sort large arrays of random integers. 2. The program generates two arrays of random integers, sorts one with merge sort and the other with quick sort, and outputs the elapsed time for each algorithm. 3. Auxiliary methods like partition, merge, and swap are included to implement the sorting algorithms.

Uploaded by

api-526463519
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views4 pages

hw5 2

1. The document describes a Java program that compares the performance of the merge sort and quick sort algorithms by timing how long each takes to sort large arrays of random integers. 2. The program generates two arrays of random integers, sorts one with merge sort and the other with quick sort, and outputs the elapsed time for each algorithm. 3. Auxiliary methods like partition, merge, and swap are included to implement the sorting algorithms.

Uploaded by

api-526463519
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

1 /*

2 * Title: hw5_2.java
3 * Abstract: Program displays the performance of the merge sort and
4 * quick sort algorithms. User will input the size of a large array
5 * of random integer numbers to be sorted by the two sorting algorithms.
6 * Name: Javier Gonzalez
7 * ID: 1218
8 * Date: 12/07/2021
9 * References:
10 * 1. Using Random Class (https://www.geeksforgeeks.org/generating-random-
numbers-in-java/)
11 * 2. Merge Sort Lesson (https://www.youtube.com/watch?v=GCae1WNvnZM &
Textbook pg.172)
12 * 3. Quick Sort Lesson (https://www.youtube.com/watch?v=COk73cpQbFQ&t=692s &
Textbook pgs.176 - 178)
13 * 4. Measuring Elapsed Time (https://howtodoinjava.com/java/date-
time/execution-elapsed-time/)
14 */
15
16 import java.util.Random;
17 import java.util.Scanner;
18
19 public class hw5_2 {
20
21    //Global constant used to convert ns to ms
22    public static final double MS_CONVERSION = 1000000.0;
23
24    public static void main(String[] args) {
25        Scanner in = new Scanner(System.in);
26        Random random = new Random();
27
28        int size, i;
29        double msTime;
30        long start, end;
31
32        //Captures input size for array of random integers to be sorted
33        System.out.print("Enter input size: ");
34        size = in.nextInt();
35        System.out.println(); //next line
36
37        //Creates two arrays of input size
38        int[] mergeNumbers = new int[size];
39        int[] quickNumbers = new int[size];
40
41        // Fills both arrays w/random integers that range from 1 - 1,000,000
42        for (i = 0; i < size; i++) {
43            int value = random.nextInt(1000000) + 1;
44            mergeNumbers[i] = value;
45            quickNumbers[i] = value;
46       }
47        //Message output
48        System.out.println("===================== Execution Time
====================");
49        System.out.print("Merge sort:\t");
50
51        //Calls mergeSort method and calculates time taken by method
52        start = System.nanoTime();
53        mergeSort(mergeNumbers);
54        end = System.nanoTime();
55
56        //Prints mergeSort execution time
57        msTime = (end - start) / MS_CONVERSION;
58        System.out.println(msTime + " milliseconds");
59
60        System.out.print("Quick sort:\t");
61
62        //Calls quickSort method and calculates time taken by method
63        start = System.nanoTime();
64        quickSort(quickNumbers, 0, quickNumbers.length - 1);
65        end = System.nanoTime();
66
67        //Prints quickSort execution time
68        msTime = (end - start) / MS_CONVERSION;
69        System.out.println(msTime + " milliseconds");
70
71      
 System.out.println("========================================================
=");
72   }
73    
74    //Recursive divide and conquer quicksort method
75    private static void quickSort(int[] quickNumbers, int start, int end) {
76        //Base case of single element array already sorted
77        if (start >= end)
78            return;
79
80        //Calls partition method to find the pivot index
81        int pivotIndex = partition(quickNumbers, start, end);
82        //Recursively calls quickSort twice to sort elements to the left and
right of pivot index
83        quickSort(quickNumbers, start, pivotIndex - 1);
84        quickSort(quickNumbers, pivotIndex + 1, end);
85   }
86
87    //Method used to partition array according to the chosen pivot
88    private static int partition(int[] quickNumbers, int start, int end) {
89        //Pivot equals the last element of the array
90        int pivot = quickNumbers[end];
91        //Creates two indexes, i & j, to keep track of partitioning
92        int i = start;
93        int j = end;
94        //If i > j, exit the loop and swap ith index with the pivot
95        while (i < j) {
96
97            while (quickNumbers[i] <= pivot && i < j) {
98                i++; //increments i if ith index in array is <= pivot and i
smaller than j
smaller than j
99           }
100
101            while (quickNumbers[j] >= pivot && i < j) {
102                j--; //decrements j if jth index in array >= pivot and i
still smaller than j
103           }
104            //Swaps values once i and j have stopped
incrementing/decrementing
105            swap(quickNumbers, i, j);
106       }
107        //Since condition no longer hold true (i < j), swap ith index with
pivot index
108        swap(quickNumbers, i, end);
109        //Returns the new pivot index of i
110        return i;
111   }
112
113    //Recursive divide and conquer mergesort method
114    private static void mergeSort(int[] mergeNumbers) {
115        int size = mergeNumbers.length;
116
117        //Base case of single element array already sorted
118        if (size == 1)
119            return;
120
121        int middle = size / 2; //middle index
122
123        //Creates left and right arrays using middle index
124        int[] leftArray = new int[middle];
125        int[] rightArray = new int[size - middle];
126
127        //Fills left and right arrays copying mergeArray
128        for (int i = 0; i < middle; i++)
129            leftArray[i] = mergeNumbers[i];
130        for (int i = middle; i < size; i++)
131            rightArray[i - middle] = mergeNumbers[i];
132
133        //Recursively divides left & right subtree
134        mergeSort(leftArray);
135        mergeSort(rightArray);
136        //Merges sorted arrays
137        merge(leftArray, rightArray, mergeNumbers);
138   }
139
140    //Method used to merge sorted left and right arrays into the single
sorted mergeNumber array
141    private static void merge(int[] leftArray, int[] rightArray, int[]
mergeNumbers) {
142        int leftSize = leftArray.length;
143        int rightSize = rightArray.length;
144
145        //Iterator variables needed for each array
146        int i = 0, j = 0, k = 0;
146        int i = 0, j = 0, k = 0;
147
148        //Loops through left & right arrays while iterator variables are
smaller than size
149        while (i < leftSize && j < rightSize) {
150            //If left index is smaller than right, merge in main array and
increment i iterator
151            if (leftArray[i] <= rightArray[j]) {
152                mergeNumbers[k] = leftArray[i];
153                i++;
154           } else { //Otherwise, right index is larger and increment j
iterator
155                mergeNumbers[k] = rightArray[j];
156                j++;
157           }
158            k++; //Increments mergeNumbers k iterator variable
159       }
160        //Adds the remaining elements in the leftover array to the main array
161        if (i == leftSize) {
162            for (; j < rightSize; j++) {
163                mergeNumbers[k] = rightArray[j]; //empties the rest of right
elements into main array
164                k++; //increments kth index
165           }
166       } else { //Does the same as above but for the left array
167            for (; i < leftSize; i++) {
168                mergeNumbers[k] = leftArray[i];
169                k++;
170           }
171       }
172   }
173
174    //Simple swap method
175    private static void swap(int[] quickNumbers, int i, int j) {
176        int temp = quickNumbers[i];
177        quickNumbers[i] = quickNumbers[j];
178        quickNumbers[j] = temp;
179   }
180 }
181

You might also like