I'm implementing Quicksort but the answer does not display correctly. I have been finding the errors but don't know where I get wrong. The answer is still 3,5,1,8,6,7,9,2. Can someone tell me what is wrong in my code?
public class quicksortJava {
public static void main (String args[]) {
int A [] = {3,5,1,8,6,7,9,2};
quicksort(A,0,A.length-1);
for(int i = 0; i < A.length; i++ ){
System.out.print(A[i]+" ");
}
}
public static void quicksort(int[]A,int start,int end){
if (start < end){
int pIndex = partition(A,start,end);
quicksort(A,start,pIndex-1);
quicksort(A,pIndex+1,end);
}
}
public static int partition(int[]A,int start,int end){
int pivot = A[end];
int pIndex = start;
for (int i = start;i < end; i++){
if (A[i] <= pivot){
swap(A[i],A[pIndex]);
pIndex++;
}
}
swap(A[pIndex],A[end]);
return pIndex;
}
public static void swap(int A,int B){
int temp = A;
A = B;
B = temp;
}
Your swap method does not work, because you are only changing the local variables "A" and "B" within the method "swap". You are not actually changing anything in the list.
Try this:
public static void swap(int a, int b) {
int tmp = list[a];
list[a] = list[b];
list[b] = tmp;
}
You'll need to change all the calls to "swap", too, so they pass an index rather than a value.
(Also, Java variables are lowercase / camelCase, not uppercase. You have multiple variables called "A", which makes everything confusing.)
Here is the correct answer
public static int partition(int[]A,int start,int end){
int pivot = A[end];
int pIndex = start;
for (int i = start;i < end; i++){
if (A[i] <= pivot){
//swap(i,pIndex);
int temp = A[i];
A[i] = A[pIndex];
A[pIndex] = temp;
pIndex++;
}
}
//swap(A[pIndex],A[end]);
int temp = A[pIndex];
A[pIndex] = A[end];
A[end] = temp;
return pIndex;
}
Related
Good evening,
My and my bud tried to figure out why the program won't bubble sort the names that we input, maybe someone could hint about it.
public static void sortDatPlane(String Ref[]){
int n = Ref.length;
int k = 1;
int j = n - 2;
int i;
while(k < n){
i = 0;
while (i <= j) {
if(notInOrder(Ref, i, i+1)){
swap(Ref, i, i+1);
}
i++;
}
k++;
}
for (String Ref1 : Ref) {
System.out.println(Ref1);
}
}
public static void swap(String Ref[], int i, int j){
String temp = Ref[i];
Ref[i] = Ref[j];
Ref[j] = temp;
}
public static boolean notInOrder(String Ref[],int i, int j){
return Ref[i].substring(0,1).compareTo(Ref[j].substring(0,1)) == 1;
}
As stated by Ken Y-N in the comments, you are only comparing the first characters of the strings (substring(0, 1) does this). Remove that part and it will probably work.
I'm new to java and as an introductory assignment on methods, a teacher asked us to create a series of methods involving arrays. He wants a "double" and an "int" for each method. I am struggling getting my linear search method to work because there seems to be an error with my swap method. I am consistantly getting errors on converting my methods from double to int. (I deleted portions of the code that is working ok, so some formatting might be off, I apologize) Any assistance would be greatly appreciated! (knowing java it's probably an obvious mistake)
ArrayUtils2.java:47: error: incompatible types: possible lossy conversion from double to int
int temp = arr[loc1];
^
ArrayUtils2.java:93: error: no suitable method found for swap(double[],int,double)
swap(arr,ix,small);
public class ArrayUtils2 {
public static void main(String[] args) {
int[] nums = {1,7,5,3,9};
displayArray(nums);
System.out.println();
displayArray(nums);
public static void swap(int[] arr, int loc1, int loc2){
int temp = arr[loc1];
arr[loc1] = arr[loc2];
arr[loc2] = temp;
System.out.println(loc2);
}
public static void swap(double[] arr, int loc1, int loc2){
double temp = arr[loc1];
arr[loc1] = arr[loc2];
arr[loc2] = temp;
}
private static int selectSmallestIndex(int[] arr, int Start){
int smallestValue = arr[Start];
for (int ix = Start; ix < arr.length; ix++){
if (arr[ix] < smallestValue) {
smallestValue = arr[ix];
}
} return smallestValue;
}
private static double selectSmallestIndex(double[] arr, int Start){
double smallestValue = arr[Start];
for (int ix = Start; ix < arr.length; ix++){
if (arr[ix] < smallestValue) {
smallestValue = arr[ix];
}
} return smallestValue;
}
public static void selectionSort(int[] arr){
for(int ix = 0; ix < arr.length; ix++){
int small = selectSmallestIndex(arr,ix);
swap(arr,ix,small);
}
}
public static void selectionSort(double[] arr){
for(int ix = 0; ix < arr.length; ix++){
double small = selectSmallestIndex(arr,ix);
swap(arr,ix,small);
}
}
public static int linearSearch(int[] arr, int num){
for (int ix = 0; ix < arr.length; ix++){
if(arr[ix] == num){
return ix;
}
}return -1;
}
public static double linearSearch(double[] arr, int num){
for (int ix = 0; ix < arr.length; ix++){
if(arr[ix] == num){
return ix;
}
}return -1;
}
}
You can't convert a double to an int as soon as a double is a floating point data type. You're tring to do int = double which is nonsense.
Here is the prototypes of your function : public static void swap(double[] arr, int loc1, int loc2) and the error says you're doing swap(double[], int, double).
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;
}
}
I have to implement an iterative quicksort in java for homework.
i've search a lot about it but i couldn't find a website with a clear explanation about how to implement an iterative quicksort.
i have found this code in java, and it sorts very well, but i can't tell how does it work, i know how the recursive quicksort works though.
i've commented the code with my questions
public static void iterativeQsort(int[] arr) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(0);
stack.push(arr.length);
while (!stack.isEmpty()) {
int end = stack.pop();
int start = stack.pop();
if (end - start < 2) continue;
int p = start + ((end-start)/2);
p = partition(arr,p,start,end);
stack.push(p+1);
stack.push(end);
stack.push(start);
stack.push(p);
}
}
private static int partition(int[] arr, int p, int start, int end) {
int l = start;
int h = end - 2; //what is h and l variables for and why h has to be end -2?
int piv = arr[p];
swap(arr,p,end-1);
while (l < h) {
if (arr[l] < piv) {
l++;
} else if (arr[h] >= piv) {
h--;
} else {
swap(arr,l,h);
}
}
int idx = h; // what is idx exactly?
if (arr[h] < piv) idx++;
swap(arr,end-1,idx);
return idx; //why return idx.
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
i'm mostly confused by the partition method, i don't know what it does.
if someone could explain me the main steps to make an iterative quicksort i'll be very happy.
Thanks for your help.
I have 2 classes written in java here they are
public class MinHeapify{
public MinHeapify(String a[], int start, int end){
minHeapify(a,start,end);
}
public static void exchange(String a[],int i,int j) {
String temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static int parent(int i) {
return (int) Math.floor((i - 1)/2);
}
public static int left(int i) {
return 2*i + 1;
}
public static int right(int i) {
return 2*(i+1);
}
public static void minHeapify(String a[], int start,int end) {
int l = left(start); int r = right(start);
int smallest=0;
if(l >= end){
smallest = (l < start)? l: start;
}
if(r >= end){
smallest = (r < smallest)? r: smallest;
}
if(smallest != start) {
exchange(a,start,smallest);
minHeapify(a,smallest,end);
}
}
}
import java.util.Scanner;
public class ReservationArray{
private String [] array = new String [50];
public ReservationArray(String [] arg){
int next = 0;
int next2 = 0;
while(arg[++next]!= null){
if(next != arg.length){
arg[next] = array[next2];
next = next++;
next2 = next2++;
}
else if(next == array.length && next!= arg.length){
String [] temp = new String[2*array.length+1];
for(int i=0; i<next; i++){
temp[i] = array[i];
array = temp;
temp = null;
}
} else{
if(next < (array.length/2)-1){
String [] temp = new String[1/2*array.length-1];
for(int i=0; i<next; i++){
temp[i] = array[i];
array = temp;
temp = null;
}
}
}
}
minHeapify(array, 0, array.length-1);
}
The error that I get when i try and compile it is " The method minHeapify(java.lang.String[], int, int) is undefined for the type ReservationArray" and I do not understand what that means, am I missing something?
MinHeapify mh = new MinHeapify();
mh.minHeapify(array, 0, array.length-1);
Since your method is static, you should call this way.
MinHeapify.(array, 0, array.length-1);
add the return type to it
public void MinHeapify(String a[], int start, int end)
and
MinHeapify.minHeapify(array, 0, array.length - 1);
The method minHeapify belongs to the MinHeapifyclass rather than ReservationArray, hence the error. As its static, you can use:
MinHeapify.minHeapify(array, 0, array.length - 1);
Alternatively, you could use a static import:
import static com.your.package.MinHeapify.minHeapify;
And use the current unqualified method call notation.
Well minHeapify is a method is the class MinHeapify. You can't access it in the class ReservationArray unless you use the reference to MinHeapify to access it.