Why is this code not working ?
The following is a recursive approach to quicksort.
Can somebody also suggest a better partitioning algorithm with pivot take as first element ?
import java.util.*;
class QuickSort
{
public static void callQuickSort(int[] array,int left,int right)
{
if(left<right)
{
int s = partition(array,left,right);
callQuickSort(array,left,s-1);
callQuickSort(array,s+1,right);
}
}
public static int partition(int[] array,int left,int right)
{
int pI = left; //pI = partition index
int pivot = array[right];
for(int i=left;i<=right-1;i++)
{
if(array[i] <= pivot)
{
swap(array[i],array[pI]);
pI++;
}
}
swap(array[pI],array[right]);
return pI;
}
static void swap(int a,int b)
{
int temp = a;
a = b;
b = temp;
}
public static void main(String args[])
{
int[] array = {7,2,1,6,8,5,3,4};//array declared
callQuickSort(array,0,7);
System.out.println("Sorted array is - ");
for(int i=0;i<8;i++)
System.out.print(array[i]+"\t");
}
}//end of class
The output is
7 2 1 6 8 5 3 4
The above code returns the array without any change. Why isn't the array changing ?
In java data is passed in method by value, not by reference, so you can't use swap method as you do.
Here is working code:
class QuickSort {
public static void callQuickSort(int[] array, int left, int right) {
if (left < right) {
int s = partition(array, left, right);
callQuickSort(array, left, s - 1);
callQuickSort(array, s + 1, right);
}
}
public static int partition(int[] array, int left, int right) {
int pI = left; //pI = partition index
int pivot = array[right];
for (int i = left; i <= right - 1; i++) {
if (array[i] <= pivot) {
int temp = array[i];
array[i] = array[pI];
array[pI] = temp;
// swap(array[i], array[pI]);
pI++;
}
}
int temp = array[pI];
array[pI] = array[right];
array[right] = temp;
// swap(array[pI], array[right]);
return pI;
}
/*static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}*/
public static void main(String args[]) {
int[] array = {7, 2, 1, 6, 8, 5, 3, 4};//array declared
callQuickSort(array, 0, 7);
System.out.println("Sorted array is - ");
for (int i = 0; i < 8; i++)
System.out.print(array[i] + "\t");
}
}//end of class
Related
I am trying to implement QuickSort on an array of ints.
All my methods function correctly except for the partition. The partition starts with getting the midpoint, then ordering, first, middle, last.
Comes out to {1,6,5,4,3,2,7}
then somewhere after this I get {1, 2, 5, 3, 4, 7, 6} as the final outcome
Can anyone tell me where I can make adjustments?
expected output should be {1,2,3,4,5,6,7}
import java.util.Arrays;
public class Test {
public static void main(String[]args) {
int [] a = {7,6,5,4,3,2,1};
quickSort(a);
System.out.println(Arrays.toString(a));
}
public static void quickSort( int [] a) {
quickSort(a,0,a.length - 1);
}
public static void quickSort(int [] a,int start,int end) {
if(start<end) {
int pivotIndex = partition(a, start, end);
quickSort(a,start,pivotIndex-1); // sort left partition
quickSort(a,pivotIndex+1,end); // sort right partition
}
}
public static int partition(int [] a, int start, int end) {
int mid =midpoint(start,end);
sortFirstMiddleLast(a,start,mid,end);
swap(a,start,end-1);
int pivotIndex = end -1;
int pivotValue = pivotIndex;
int indexFromLeft = start +1;
int indexFromRight = end -2;
boolean done = false;
while (!done) {
while (a[indexFromLeft]<a[pivotValue]) {
indexFromLeft++;
}
while (a[indexFromRight]>a[pivotValue]) {
indexFromRight--;
}
if (indexFromLeft < indexFromRight) {
swap(a,indexFromLeft,indexFromRight);
indexFromLeft++;
indexFromRight--;
}
else {
done=true;
}
}
swap(a,pivotIndex,indexFromLeft);
pivotIndex=indexFromLeft;
return pivotIndex;
}
public static void sortFirstMiddleLast(int [] a, int start, int mid, int end) {
if (a[start]>a[mid]) {
swap(a,start,mid);
}
else if (a[mid]>a[end]) {
swap(a,mid,end);
}
else if (a[start]>a[end]) {
swap(a,start,end);
}
else if(a[start] > a[mid]) {
swap (a,start,mid);
}
}
private static void swap(int[] a, int first, int second) {
int temp = a[first];
a[first] = a[second];
a[second] = temp;
}
private static int midpoint(int first, int last) {
return first + (last - first) / 2;
}
}
check whether if start =< array.size -1 and end >= 0 before execute futher after lines :
int indexFromLeft = start +1;
int indexFromRight = end -2;
terminate recursions on that condition.
If you use the class created below, you won't have any problems.
class QuickSort{
int partition(int arr[], int low, int high)
{
int pivot = arr[high];
int i = (low-1);
for (int j=low; j<high; j++)
{
if (arr[j] <= pivot)
{
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
return i+1;
}
void sort(int arr[], int low, int high)
{
if (low < high)
{
int pi = partition(arr, low, high);
sort(arr, low, pi-1);
sort(arr, pi+1, high);
}
}
Try this one
swap(a,start,end-1);
int pivotIndex = end -1; // removed -1
int pivotValue = pivotIndex;
int indexFromLeft = start +1; // removed +1
int indexFromRight = end -2; // removed -2
public static int partition(int [] a, int start, int end) {
int mid =midpoint(start,end);
sortFirstMiddleLast(a,start,mid,end);
swap(a,start,end-1);
int pivotIndex = end ;
int pivotValue = pivotIndex;
int indexFromLeft = start ;
int indexFromRight = end;
boolean done = false;
while (!done) {
while (a[indexFromLeft]<a[pivotValue]) {
indexFromLeft++;
}
while (a[indexFromRight]>a[pivotValue]) {
indexFromRight--;
}
if (indexFromLeft < indexFromRight) {
swap(a,indexFromLeft,indexFromRight);
indexFromLeft++;
indexFromRight--;
}
else {
done=true;
}
}
swap(a,pivotIndex,indexFromLeft);
pivotIndex=indexFromLeft;
return pivotIndex;
}
I have a simple rotation function which takes an array and a number to rotate the numbers left
e.g. [1,2,3,4,5] & 2 - output: [3,4,5,1,2].
I want to know the most efficient way of completing this function, whether it would be to convert the int array into a string a splice it or whether to copy the array or to convert to an List<Integer>.
If anyone wants additional information please ask!
my solution at the moment:
static int[] rotLeft(int[] a, int d) {
int lengthOfArray = a.length;
int[] temp = new int[lengthOfArray];
for(int i = 0; i < lengthOfArray; i++){
int newLocation = (i + (lengthOfArray - d)) % lengthOfArray;
temp[newLocation] = a[i];
}
return temp;
}
Simple way to do it with O(n) complexity is as below along with handling of valid shifts int[] arr: is an int array, n=length of an array, d=how many shifts required.
public int[] leftRotate(int[] arr, int n, int d) {
int rot = 0;
int[] marr = new int[n];
if (d < 0 || d == 0 || d>n) {
return arr;
}
else {
for (int i = 0; i < n; i++) {
if (i < n - d) {
marr[i] = arr[i + d];
} else {
marr[i] = arr[rot];
rot++;
}
}
return marr;
}
}
public void GetArray(int[] arr, int n, int d) {
int[] arr1 = leftRotate(arr, n, d);
for (int j : arr1) {
System.out.println(j);
}
}
public static void main(String args[]) {
int[] arr = { 1,2,3,4,5 };
int n = arr.length;
Test2 obj = new Test2();
obj.GetArray(arr, n, 2);
}
Why don't you try this one
void Rotate(int arr[], int d, int n)
{
for (int i = 0; i < d; i++)
leftRotatebyOne(arr, n);
}
void leftRotatebyOne(int arr[], int n)
{
int i, temp;
temp = arr[0];
for (i = 0; i < n - 1; i++)
arr[i] = arr[i + 1];
arr[i] = temp;
}
and to call this invoke method like below
int arr[] = { 1, 2, 3, 4, 5 };
Rotate(arr, 2, 5);
I am trying to implement quick sort using Java.The partition function does what it should do.That is,partition the array around the pivot(I've chosen the element as the pivot). But the final output is not in sorted order.I cannot figure the error out.Can someone help?
public class Quick_sort {
public static int arr[] = {11, 2, 7, 1, 5, 4, 12, 65, 23};
public static int temp = 0;
public static void main(String args[]) {
int p=0;
int r=arr.length;
quick_sort(p,r);
for(int i: arr)
System.out.println(i);
}
public static int partition(int p, int r) {
if(p < r) {
int pivot=arr[p];
int i=1;
for(int j=1;j<r;j++) {
if(arr[j]<pivot) {
temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
i++;
}
}
temp=arr[i-1];
arr[i-1]=arr[p];
arr[p]=temp;
for(int m=0;m<r;m++) {
if(arr[m]==pivot) {
temp=m;
}
}
}
return temp;
}
public static void quick_sort(int p,int r) {
if(p>=r) return;
int index=partition(p,r);
quick_sort(p,index-1);
quick_sort(index+1,r-1);
}
}
In your last line
quick_sort(index+1,r-1);
You skip the last element of the array. But the last element should be sorted as well. Try it with:
quick_sort(index+1,r);
And it is better to adapt the variables i and j in the partition method to the current processed part of the array.
So I tried to fix it. Try it with (main function):
int r=arr.length-1;
and change the partition function to:
public static int partition(int p, int r) {
if(p < r) {
int pivot=arr[p];
int i= p ;
for(int j=(p+1);j<=r;j++) {
if(arr[j]<pivot) {
temp=arr[j];
arr[j]=arr[i + 1];
arr[i + 1] = arr[i];
arr[i] = temp;
i++;
}
}
temp = i;
}
return temp;
}
as well as the in the quick-sort method:
quick_sort(p,index-1);
quick_sort(index+1,r);
Do you see your problem? Your main problem was to not adapt the variables to the smaller parts you are actually looking at at the moment. It did well for the first partition round, but not for the following, as you had the former variables.
This is a complete example of a QuickSort implementation :
public class QuickSort {
public static void main(String[] args) {
int[] x = { 9, 2, 4, 7, 3, 7, 10 };
System.out.println(Arrays.toString(x));
int low = 0;
int high = x.length - 1;
quickSort(x, low, high);
System.out.println(Arrays.toString(x));
}
public static void quickSort(int[] arr, int low, int high) {
if (arr == null || arr.length == 0)
return;
if (low >= high)
return;
// pick the pivot
int middle = low + (high - low) / 2;
int pivot = arr[middle];
// make left < pivot and right > pivot
int i = low, j = high;
while (i <= j) {
while (arr[i] < pivot) {
i++;
}
while (arr[j] > pivot) {
j--;
}
if (i <= j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
// recursively sort two sub parts
if (low < j)
quickSort(arr, low, j);
if (high > i)
quickSort(arr, i, high);
}
}
you can find more here.
I am getting a StackOverflowError for this code. It says lines 184/185, which is where I initialize the split position (see below) and call the first recursive quickSort method. I can see that the code is having trouble exiting from the recursion, but I'm not sure where that is happening. Each time I call quickSort, it is on a smaller partition.
import java.util.*;
public class java2{
public static int MAXINT = 10000;
public static int[] intArray = new int[MAXINT];
public static int index;
public static long comparisons;
public static void main(String[] args)
{
System.out.println("SORTING ALGORITHM: Quicksort");
// Create a random array of integers and sort using the CombSort algorithm
// Print the number of items and comparisions
for(index = 10; index <= 10000; index = index * 10)
{
if (index == 10)
for(int i = 0; i < index; i++)
System.out.print(intArray[i] + " ");
comparisons = 0;
generate(intArray, index);
quickSort(intArray, 0, index - 1);
output(comparisons);
}
}
// Generate an array of random values between 0 and 10000
public static void generate(int[] valueArray, int count)
{
Random generator = new Random();
for(int temp = 0; temp < count; temp++)
{
valueArray[temp] = generator.nextInt(MAXINT) + 1;
}
}
// Print the number of values in the array and the number of comparisons
public static void output(long count)
{
System.out.println("Number of values in array: " + index);
System.out.println("Number of comparisons required: " + count);
System.out.println();
}
//Swap the given values and then assign them to the correct place in the array
public static void swap(int[] value, int i, int j)
{
int temp = value[i];
value[i] = value[j];
value[j] = temp;
}
//Implement Quicksort algorithm
public static void quickSort(int[] value, int startIndex, int endIndex)
{
int r = endIndex;
int l = startIndex;
int s;
if (l < r)
{
s = partition(intArray, l, r);
quickSort(intArray, l, s - 1); // StackOverflowError here
quickSort(intArray, s + 1, r);
}
}
//Partition an array into two parts
public static int partition(int[] value, int startIndex, int endIndex)
{
int r = endIndex;
int l = startIndex;
int p = value[l];
int i = l;
int j = r + 1;
while(i < j)
{
while(value[i] < p)
{
i++;
comparisons++;
}
while(value[j] > p)
{
j--;
comparisons++;
}
swap(value, i, j);
}
swap(value, i, j);
swap(value, l, j);
return j;
}
} // end main
Here are a few things to get you started with debugging.
You haven't posted your swap, but it's almost certainly incorrect. The way you're using it, its prototype would be void swap(int, int, int, int) which means it cannot have any effect on the value array. Try something like this:
public static void swap(int[] value, int i, int j) {
int temp = value[i];
value[i] = value[j];
value[j] = temp;
}
and use it like this:
swap(value, i, j);
Next, get the length=10 case correct. Print out the full array before and after sort, verify that the output is correct. When I run your code on an all zero array I get an infinite loop.
Next, if you're still having problems, add print statements!
By restructuring the partition method, the problem has been fixed:
public static int partition(int[] value, int p, int r)
{
int x = value[p];
int i = p - 1;
int j = r + 1 ;
while (true)
{
do
{
j--;
comparisons++;
}
while (value[j] > x);
do
{
i++;
comparisons++;
}
while (value[i] < x);
if (i < j)
{
swap(value, i, j);
}
else
return j;
}
}
Here is my code:
public class Main
{
public static void main(String[] args)
{
int[] temp = {4,2,6,4,5,2,9,7,11,0,-1,4,-5};
quickSort(temp);
for(int s : temp) System.out.println(s);
}
public static void quickSort(int[] data)
{
quickSort(data, 0, data.length);
}
public static void quickSort(int[] data, int first, int n)
{
int p, n1, n2;
if(n > 1)
{
p = partition(data, first, n);
n1 = p - first;
n2 = n - n1 - 1;
quickSort(data, first, n1);
quickSort(data, p+1, n2);
}
}
private static int partition(int[] A, int first, int n )
{
int right = first + n - 1;
int ls = first;
int pivot = A[first];
for(int i = first+1; i <= right; i++)
{
if(A[i] <= pivot)
// Move items smaller than pivot only, to location that would be at left of pivot
{
ls++;
swap(A[i], A[ls]);
}
}
swap(A[first], A[ls]);
return ls;
}
private static void swap(int i, int j)
{
int temp = i;
i = j;
j = temp;
}
}
After running this program, it does not sort the array and prints the same array without sorting.
4
2
6
4
5
2
9
7
11
0
-1
4
-5
What is the wrong in this implementation?
The problem is that your swap() function doesn't actually swap elements in an array, it just swaps the values in two integer variables. Integers are passed in Java by value, not by reference.
Replace this with a swap function that re-assigns the array values such as:
private static void swap(int[] array, int pos1, int pos2) {
int temp = array[pos1];
array[pos1] = array[pos2];
array[pos2] = temp;
}
Your swap function passes its parameters by value. Everthing is pass-by-value in java.
Your swap function needs to effectively pass by reference: See #matt b's answer above.
See Is Java pass by reference? for a good explanation of parameter passing.