I am (for homework, if that influences how the answers are given) supposed to be writing a class for quicksort to sort an array from a txt or dat file provided by the user. I present the user with an menu option in the driver class to select sort type and then pass the array to the quicksort class for sorting, after which it is returned back to the driver class to be written to a file. I believe the return is operating correctly, as I get the unsorted array printed to the file, however it only appears to be making one pass through the quicksort loop (determined by only one printing of the "Last Loop" string to the console.
The addition bits of code are part of the assignment, allowing a user to select Insertion sort to complete the sort if only 50 or 100 items remain in the unsorted array based on user choice. I have tried running this program commenting those two if statements out and still the program does not correctly sort. I am certain the input is read correctly as I have an addition HeapSort class that does sort correctly, and insertion sort returns correctly if that option is selected and the file size is less than 50 or 100 ints. I cannot seem to get the QuickSort of a larger file to trigger though.
class Quicksort{
int partition(int arr[], int lb, int ub){
int i = lb, j = ub;
int temp;
int pivot = arr[0];
while (i <= j) {
while (arr[i] < pivot){
i++;
}while(arr[j] > pivot){
j--;
}if (i <= j){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}return i;
}
int[] quicksort(int arr[], int lb, int ub, boolean insertLarge, boolean insertSmall){
if (insertLarge && arr.length <= 100){
System.out.println("Large");
insertionSort(arr);
}
else if (insertSmall && arr.length <= 50){
System.out.println("Small");
insertionSort(arr);
}
else{
int[] intArrCopy = new int[arr.length-1];
for (int z = 1; z < intArrCopy.length; z++){
intArrCopy[z-1] = arr[z];
}
System.out.println("Last Loop");
int index = partition(arr, lb, ub);
if (lb < index-1){
quicksort(intArrCopy, lb, index-1, insertLarge, insertSmall);
}if (index < ub){
quicksort(intArrCopy, index, ub, insertLarge, insertSmall);
}
}return arr;
}
public static void insertionSort(int x[]){
int h, k, y;
for (k=1; k < x.length; k++){
y = x[k];
for (h = k-1; h>=0 && y < x[h]; h--){
x[h+1] = x[h];
}x[h+1] = y;
}
}
}
And how it is being called from driver class:
private static void processChoice(int choice, int[] intArr){
switch (choice){
case 1:
p = intArr.length;
output = new int[p];
startTime = System.nanoTime();
output = quick.quicksort(intArr, intArr[0], intArr[p-1], insertLarge, insertSmall);
endTime = System.nanoTime();
System.out.println("Time Taken: "+(endTime-startTime)+" nanoseconds.");
break;
}
}
Assuming a hybrid sort, try something like this:
void quicksort(int arr[], int lb, int ub){
if ((ub-lb) < 100){ // < 32 may be fastest
System.out.println("Large");
insertionSort(arr, lb, ub);
return;
}
int index = partition(arr, lb, ub);
if (lb < index-1)
quicksort(arr, lb, index-1);
if (index < ub)
quicksort(arr, index, ub);
}
public static void insertionSort(int x[], int lb, int ub){
int h, k, y;
for (h = lb+1; h <= ub; h++){
y = x[h];
for (k = h; k > lb && x[k-1] > y; k--)
x[k] = x[k-1];
x[k] = y;
}
}
Related
I implemented a QuickSort Algorithm which only works for 7 elements and then gives a StackOverflow Error for 8 elements or more. Goes into an infinite loop. Works fine for the number of elements that are present in the array but if I add one more element, it returns a StackOverflow Error
Here is my code:
public class QuickSort
{
public void main()
{
QuickSort o = new QuickSort();
int arr[] = {8,5,2,10,1,7,3};
o.sort(arr,0,arr.length-1);
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
}
void sort(int []arr,int l,int h)
{
if(l<h)
{
int pi = partition(arr,l,h);
sort(arr,l,pi);
sort(arr,pi+1,h);
}
}
int partition(int arr[],int l,int h)
{
int pivot = arr[l];
int i=l,j=h;
while(i<j)
{
while(arr[i]<=pivot)
{
i++;
}
while(arr[j]>pivot)
{
j--;
}
if(i<j)
{
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
int t = arr[j];
arr[j] = pivot;
arr[l] = t;
return j;
}
}
I believe the problem is that you don't put the pivot in the right place.
Here is your code with a small change:
int partition(int arr[],int l,int h){
int pivot = arr[l];
int i= l,j=h;
while(i < j){
while( i < j && arr[i]<=pivot){ i++;}
while( i < j && arr[j]>pivot){ j--;}
if(i< j){
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
//here it is determined where the pivot should go. It is easiest to understand with an example
//after the loop arr can be 3 1 2 4 5
//the pivot being 3 should be switched with the number 2 but index j sometimes points to number 2 and sometimes to number 4
//the following code determines the desired index
int lowerInd = arr[j] <= pivot ? j : j - 1;
int t = arr[lowerInd];
arr[lowerInd] = arr[l];
arr[l] = t;
return lowerInd;
}
Also, in your sort method, call sort(arr,l,pi - 1); instead of sort(arr,l,pi);
void sort(int[] arr,int l,int h){
if(l<h){
int pi = partition(arr,l,h);
sort(arr,l,pi - 1);
sort(arr,pi+1,h);
}
}
Attempting to implement QuickSort using Hoare Partition Scheme, but I am running into a problem where changing the index of the pivot causes overflow, regardless of array size. Code:
public void quickSort(int[] l, int min, int max){
if (min < max){
int p = partition(l, min, max);
quickSort(l, min, p);
quickSort(l, p+1, max);
}
}
public int partition(int[] l, int min, int max){
int pivot = l[min];
int i = min - 1;
int j = max +1;
while(true){
do{
i++;
}while(l[i] < pivot);
do{
j--;
}while(l[j] > pivot);
if (i >= j) {
return j;
}
//Swap
int temp = l[i];
l[i] = l[j];
l[j] = temp;
}
}
This implementation chooses the low-index (named min here) as the pivot element, and this works just fine. However, changing the pivot element to any other index, causes a StackOverflow Error regardless of the size of the array that is being sorted. (Error refers to line 3, where partition() is called) I would preferably have the pivot element chosen at random within the (min,max) range. What is causing this?
EDIT:
The array used is generated as follows:
public static int[] generateRandomArray(int size, int lower, int upper){
int[] random = new int[size];
for (int i = 0; i < random.length; i++) {
int randInt = ThreadLocalRandom.current().nextInt(lower, upper+1);
random[i] = randInt;
}
return random;
}
In one of the Overflow cases I used this:
genereateRandomArray(10, 0, 9);
For some concrete examples, running the code above but changing the pivot element to say, l[max-1] or l[min+1], l[min+2] etc gives StackOverflow on my end.
The solution to my problem was as user MBo pointed out to swap the pivot element to the first index of the array, as the algorithm itself relies on the pivot being on index 0. This is what I had overlooked.
(int i = min - 1; is correct however, and stays that way.)
We can see that at the first step i becomes equal to min, comparison of pivot element with itself fails and increment does not occur more:
int pivot = l[min];
int i = min - 1;
...
do{
i++;
}while(l[i] < pivot);
Exclude pivot element from comparison (int i = min;) and exchange it with partition one (seems l[j]) at the end
Using the middle value for pivot is working for me. Here is a complete example:
public static void quickSort(int[] l, int min, int max){
if (min < max){
int p = partition(l, min, max);
quickSort(l, min, p);
quickSort(l, p+1, max);
}
}
public static int partition(int[] l, int min, int max){
int pivot = l[(min+max)/2];
int i = min - 1;
int j = max + 1;
while(true){
do{
i++;
}while(l[i] < pivot);
do{
j--;
}while(l[j] > pivot);
if (i >= j) {
return j;
}
int temp = l[i];
l[i] = l[j];
l[j] = temp;
}
}
public static int[] generateRandomArray(int size, int lower, int upper){
int[] random = new int[size];
for (int i = 0; i < random.length; i++) {
int randInt = ThreadLocalRandom.current().nextInt(lower, upper+1);
random[i] = randInt;
}
return random;
}
public static void main(String[] args) {
int[] A = generateRandomArray(10, 0, 9);
long bgn, end;
bgn = System.currentTimeMillis();
quickSort(A, 0, A.length-1);
end = System.currentTimeMillis();
for(int i = 1; i < A.length; i++){
if(A[i-1] > A[i]){
System.out.println("failed");
break;
}
}
System.out.println("milliseconds " + (end-bgn));
}
So I'm implement a quickselect algorithm that chooses a good pivot each time. What it does is divide the array into groups of 5, sorts each groups and finds the median. It then takes the medians of each group, groups those values up and then finds the median of medians. Here's what I have:
private static int pickCleverPivot(int left, int right, int[] A){
int index = 0;
int n = right-left;
if (n <= 5) {
Arrays.sort(A);
index = n/2;
return index;
}
int numofMedians = (int) Math.ceil(n/5);
int[] medians = new int[numofMedians];
int[] groups = new int[5];
for(int i = 0; i < numofMedians; i++) {
if (i != numofMedians - 1){
for (int j = 0; j < 5; j++){
groups[j] = A[(i*5)+j];
}
medians[i] = findMedian(groups, 5);
} else {
int numOfRemainders = n % 5;
int[] remainder = new int[numOfRemainders];
for (int j = 0; j < numOfRemainders; j++){
remainder[j] = A[(i*5)+j];
}
medians[i] = findMedian(groups, 5);
}
}
return pickCleverPivot(left, left+(numofMedians), medians);
}
public static int findMedian(int[] A, int n){
Arrays.sort(A);
if (n % 2 == 0) {
return (A[n/2] + A[n/2 - 1]) / 2;
}
return A[n/2];
}
private static int partition(int left, int right, int[] array, int pIndex){
//move pivot to last index of the array
swap(array,pIndex,right);
int p=array[right];
int l=left;
int r=right-1;
while(l<=r){
while(l<=r && array[l]<=p){
l++;
}
while(l<=r && array[r]>=p){
r--;
}
if (l<r){
swap(array,l,r);
}
}
swap(array,l,right);
return l;
}
private static void swap(int[]array, int a, int b){
int tmp = array[a];
array[a] = array[b];
array[b] = tmp;
}
So it works like it's supposed to but now I'm wondering if it's possible to get it to run in linear O(n) time. I'm currently comparing this code to just choosing a random pivot. On smaller arrays this code runs faster but on larger arrays, choosing a random pivot is faster. So is it actually possible to make this run in O(n) time or is that just in theory and if it's not possible for it to run that fast then is this method running as fast as it could.
For school I have to write a quicksort for an Array of strings. I think my partition is good but I keep getting error with the recursion.
public static int partition(String[] input, int max) {
// pivot is dividing point
// I keeps track of lesser values
// count is just a counter
// Pivots in place
int pivot = 0;
int i = 1;
int count = 1;
while (count <= max) {
if (input[count].compareTo(input[pivot]) < 0) {
input[i] = input[count];
i = i + 1;
}
if (count == max) {
input[i] = input[pivot];
input[pivot] = input[i];
}
count++;
}
return pivot;
}
public static void qSort(String[] input) {
int index = partition(input, input.length - 1);
int count = 0;
if (count < index - 1) {
partition(input, index - 1);
}
if (index + 1 < count && count < input.length) {
partition(input, input.length - 1);
}
count++;
}
Your implementation has a lot of mistakes. First of all, you're always choosing the pivot to be the element at index 0 of the array. The idea of quicksort is that you choose some pivot, partition the array around it, then recursively apply quicksort on both partitions around the chosen pivot. How do you identify the start and end of the partitions you'll call quicksort recursively on? You need to pass those as arguments to your partition method as others have mentioned in the comments, same thing for the quicksort method itself.
public void swap (String [] array, int i, int j) {
String tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
public static int partition (String [] array, int low, int high) {
String pivot = array[low];
int index = low+1;
for (int i = low+1; i <= high; i++) {
if (pivot.compareTo(array[i]) > 0) {
swap(array, i, index);
index++;
}
}
swap(array, low, index-1);
return index-1;
}
public static void qsort(String [] array, int low, int high) {
if (low < high) {
int p = partition(array, low, high);
qsort(array, low, p);
qsort(array, p+1, high);
}
}
Obviously this isn't the best way to choose the pivot as some arrays will make the algorithm perform very poorly. A better method would be to use a random pivot each time.
I was implementing a merge sort in Algorithms in Java 4th edition.
My basic merge sort works, and I want to improve the algorithm by using insertion sort when the array size is less than 7.
I thought it is obvious an efficient improvement, but actually the original one is faster than the improved one for large data.
Here is my improved merge sort, CUTOFF = 7:
private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {
// Copy to aux[]
for (int i = lo; i <= hi; i++) {
aux[i] = a[i];
}
// Merge back to a[]
int i = lo, j = mid + 1;
for (int k = lo; k <= hi; k++) {
if (i > mid) a[k] = aux[j++];
else if (j > hi) a[k] = aux[i++];
else if (less(aux[i], aux[j])) a[k] = aux[i++];
else a[k] = aux[j++];
}
}
private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {
// #1 improvement
// Stop condition for this recursion.
// This time we add a CUTOFF, when the items in array
// is less than 7, we will use insertion sort.
if (hi <= lo + CUTOFF - 1) {
Insertion.sort(a, lo, hi);
return;
}
int mid = lo + (hi - lo) / 2;
sort(a, aux, lo, mid);
sort(a, aux, mid + 1, hi);
if (!less(a[mid+1], a[mid])) return;
merge(a, aux, lo, mid, hi);
}
public static void sort(Comparable[] a) {
Comparable[] aux = new Comparable[a.length];
sort(a, aux, 0, a.length - 1);
}
The insertion sort code:
public static void sort(Comparable[] a, int lo, int hi) {
for (int i = lo; i <= hi; i++) {
for (int j = i; j > 0 && less(a[j], a[j - 1]); j--) {
exch(a, j, j - 1);
}
}
}
I used a SortCompare.java to compare the execute time:
public class SortCompare {
public static double time(String alg, Comparable[] a) {
Stopwatch timer = new Stopwatch();
if (alg.equals("Insertion")) Insertion.sort(a);
if (alg.equals("Selection")) Selection.sort(a);
if (alg.equals("Shell")) Shell.sort(a);
if (alg.equals("Merge")) Merge.sort(a);
if (alg.equals("MergeWithImprovements")) MergeWithImprovements.sort(a);
//if (alg.equals("Quick")) Quick.sort(a);
//if (alg.equals("Heap")) Heap.sort(a);
if (alg.equals("InsertionWithSentinel")) InsertionWithSentinel.sort(a);
return timer.elapsedTime();
}
public static double timeRandomInput(String alg, int N, int T) {
// Use alg to sort T random arrays of length N.
double total = 0.0;
Double[] a = new Double[N];
for (int t = 0; t < T; t++) {
for (int i = 0; i < N; i++) {
a[i] = StdRandom.uniform();
}
total += time(alg, a);
}
return total;
}
public static void main(String[] args) {
String alg1 = args[0];
String alg2 = args[1];
int N = Integer.parseInt(args[2]);
int T = Integer.parseInt(args[3]);
double t1 = timeRandomInput(alg1, N, T); // Total for alg1
double t2 = timeRandomInput(alg2, N, T);
StdOut.printf("For %d random Doubles\n %s is", N, alg1);
StdOut.printf(" %.1f times faster than %s\n", t2/t1, alg2);
}
}
I generated 100 arrays with 10000 elements each. The original merge sort is 30 times faster than the improved one!
You insertion sort function is definitely wrong. Note the j > 0 end condition. You pass in [lo..hi] but your code can iterate j all the way down to 1. I think you want something like:
public static void sort(Comparable[] a, int lo, int hi) {
for (int i = lo + 1; i <= hi; i++) {
for (int j = i; j > lo && less(a[j], a[j - 1]); j--) {
exch(a, j, j - 1);
}
}
}