Quicksort in Java - java

I'm supposed to do a quicksort algorithm in java to sort the array {50, 20, 65, 30, 75, 25, 90}. Here is what I have so far:
public class QuickSort {
public static int partition(int arrayName[], int down, int up){
int i = down, j = up;
int temp;
int pivot = arrayName[(down + up) / 2];
while (i <= j){
while (arrayName[i] < pivot)
i++;
while (arrayName[j] > pivot)
j--;
if (i <= j){
temp = arrayName[i];
arrayName[i] = arrayName[j];
arrayName[j] = temp;
i++;
j--;
}
}
return i;
}
public static void main(String[] args) {
int [] arrayName = {50, 20, 65, 30, 75, 25, 90};
System.out.println(partition(arrayName, down, up));
}
}
I'm getting an error on the print statement (seem to have a lot of trouble with these) that says down and up cannot be resolved to variables. How can I fix it so I can successfully print the sorted list?

It's because you haven't defined any variables named down and up in your main method. You should specify values instead of those names.

Your partition method returns an int. Instead, change your method body so that it returns the newly sorted array (and make sure you change the return type in the method declaration too, else you'll get an error). Furthermore, you need to define up and down in the main method.
For instance:
public static int[] partition(...)
{
...
return arrayname;
}
Edit: furthermore, you may need to use Arrays.toString() to output the array correctly (it's been a while since I used Java). eg:
System.out.println(Arrays.toString(partition(arrayName, up, down)));

you are getting index out of bound ,
because up and down are non initialized and in java it makes them 0
so down goes at j :
while(arrayName[j]<pivot){ //<--- this will thow exception as j starts at 0
j--;
which leads to -1 and accessing the array at arrayName[-1] is out of bound.

Related

How I could find the maxim value of an array with recursive without having an index?

I have that method valorMaxim([1, 5, 252, 24, 7, 82, 3]) returns 252.
I don't know how to do it. I have been thinking if I could decrease the array length.
public static int valorMaxim(int arr[]){
int max;
if(arr.length==1)
return arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] < arr[i+1]) {
max=arr[i+1];
return arr[i+1];
}
}
return valorMaxim(arr);
//Retorna el valor màxim en un array no buit d’enters.
}
I modified the accepted answer to Finding Max value in an array using recursion.
As you suggested (i.e. decrease the array length with each recursive method invocation), I create a copy of the method parameter whose length is one less than the parameter and remove the first element. Then I recursively call the method with the array copy.
public class Main {
public static int valorMaxim(int arr[]){
if (arr.length == 1) {
return arr[0];
}
else {
int[] tmp = new int[arr.length - 1];
System.arraycopy(arr, 1, tmp, 0, tmp.length);
return Math.max(arr[0], valorMaxim(tmp));
}
}
public static void main(String[] args) {
System.out.println(valorMaxim(new int[]{1, 5, 252, 24, 7, 82, 3}));
}
}
Basically, the recursive idea is:
If the array has length 1, return the only element;
Otherwise, split the array into x the first element, and xs the rest;
Find the maximum element within xs, compare it to x and yield the greater.
There are two ways to achieve such a "split":
Create a new copy of part of the array for xs
You can either use System.arraycopy (see answer by #Abra) or Arrays.copyOfRange, which is simpler:
int x = arr[0];
int[] xs = Arrays.copyOfRange(arr, 1, arr.length);
And now we lookup the maximum element within xs (which is valorMaxim(xs)), and compare it to x as the final result:
return Math.max(x, valorMaxim(xs));
Put everything together, and don't forget to add a length checker:
public static int valorMaxim(int arr[])
{
if (arr.length == 1) return arr[0];
int x = arr[0];
int[] xs = Arrays.copyOfRange(arr, 1, arr.length);
return Math.max(x, valorMaxim(xs));
}
And that's it! Since we have the length checker in the first place,
we can safely make sure xs would never be empty, and hence valorMaxim(xs) would
never result in ArrayIndexOutOfBoundsException.
Set a boundary for the array
You may have found that copying a new array at each time could be time- and memory-consuming.
Instead of creating a physical copy for xs, we can conceptualise the idea
and use a bounded array instead. We would need to define a helper method to do so:
private static int findMaxBound(int arr[], int startFrom)
{
// does "xs" have length 1?
if (startFrom == arr.length - 1) return arr[startFrom];
int x = arr[startFrom];
int maxInXs = findMaxBound(arr, startFrom + 1);
return Math.max(x, maxInXs);
}
And then we can define valorMaxim as
public static int valorMaxim(int arr[])
{
return findMaxBound(arr, 0);
}
In the end, we did not create any new copies of arr
but uses different ranges of itself and treat them as xs throughout the process.

Int array sorting itself

import java.util.ArrayList;
public class Paaohjelma {
public static int pienin(int[] taulukko) {
int temp, size;
size = taulukko.length;
for(int i = 0; i<size; i++ ){
for(int j = i+1; j<size; j++){
if(taulukko[i]>taulukko[j]){
temp = taulukko[i];
taulukko[i] = taulukko[j];
taulukko[j] = temp;
}
}
}
return taulukko[0];
}
public static int pienimmanIndeksi(int[] taulukko) {
ArrayList<Integer> tauli = new ArrayList<>();
for (int i : taulukko) {
tauli.add(i);
}
return tauli.indexOf(Paaohjelma.pienin(taulukko));
}
public static int pienimmanIndeksiAlkaen(int[] taulukko, int aloitusIndeksi) {
// this methods should get the index of smallest value starting from specified index
int[] tempTauli = taulukko;
tempTauli = new int[tempTauli.length - aloitusIndeksi];
// this gets the right values to temporary array
if (aloitusIndeksi > 0) {
int index = 0;
int indexTauli = 0;
for(int value : taulukko) {
if(index >= aloitusIndeksi) {
tempTauli[indexTauli] = taulukko[index];
indexTauli++;
}
index++;
}
}
// values added are automatically sorted from smallest to largest?
// this shouldn't be, array should be 5, 99, 3, 12 but is shown as 3, 5, 12, 99
for(int inty : tempTauli) {
System.out.println(inty);
}
// get the index of smallest value in array
// index is 0 should be 2
int index = Paaohjelma.pienimmanIndeksi(tempTauli);
// return index of smallest value (add starting index to get the index of smallest value in the original array when starting from specified index)
return index+aloitusIndeksi;
}
public static void main(String[] args) {
// test code
int[] taulukko = {3, 1, 5, 99, 3, 12};
int minIndex = Paaohjelma.pienimmanIndeksi(taulukko);
System.out.println("Pienin: " + Paaohjelma.pienin(taulukko));
System.out.println("Pienimmän indeksi: " + minIndex);
System.out.println(Paaohjelma.pienimmanIndeksiAlkaen(taulukko, 2));
}
}
Hello! I'm doing some programming course work for school and have been stuck in this particular part for couple hours. So I decided it would be best for someone else to take a look and provide some light why my approach for this problem isn't working.
What should happen: class method PienimmanIndeksiAlkaen should return the index of smallest value in provided int array starting from specified index.
The main problem I have been having is that the array seems to be automatically sorting itself and I have no idea what is possible causing this. I have commented the relevant part of the code and would be more than happy if someone could explain why this is happening and what possible could be done to prevent this.
The reason your array is sorted is when you call
System.out.println("Pienin: " + Paaohjelma.pienin(taulukko));
you sort the array.
When you pass the array into this function, you aren't actually passing the value of the array, but the pointer to the array - the address of the array in memory. This is the difference between passing parameters by value or by reference.
How do you know if the value is passed by value or by reference?
As a rule of thumb:
primitive values - i.e. int, double, etc. will be passed by value - their value will be copied and passed to the function.
Any other type, namely arrays and classes, will be passed by reference - the address of the value in memory will be passed to the function, thus any change to the value inside the function will affect it when the function ends too.
Read more here

How do I count all possible sums of array elements

I’m kind of stuck with my code and I can’t find where the problem is. My task is to find the closest sum in the array to the x value and amount of indexes to sum must not exceed n-value. Indexes to sum might not be consecutive, so the closest sum might be indexes(0,2,3) instead of (0,1,2).
I’ve written some code, but it does not work with n value bigger than 4.
In my code value of sums(n) if called «towns» and x value is called «miles».
Here comes the code
for(int i=0;i<ls.size();i++){
sum=ls.get(i);
counterTowns=1;
if(sum<miles&&counterTowns<towns){
for(int j=i+1;j<ls.size();j++){
sum+=ls.get(j);
counterTowns++;
if(counterTowns==towns){
if(sum<=miles){
if(sum>temp){
result=sum;
}
temp=result;
}
sum=ls.get(i);
counterTowns=1;
if(towns>2){ // I think the problem is in this line
j--;
}
}
}
}
}
To be more clear, "ls" is the ArrayList of Integers.
For example:
ArrayList is {50, 55, 56, 57, 58};
And towns=3, miles = 163 expected output is 163 which is the sum of 50+56+57.
When towns <=3 it works just fine with different miles, but if towns >3 it does not provide right output.
For example, if ArrayList is{91, 74, 73, 85, 73, 81, 87}
and miles= 331 and towns is 4 result is 30 instead of 331( result of 91+74+85+81).
I hope my question is clear and if not feel free to ask any questions.
Thank you in advance.
Peace and love!!!
Basically you want all the combinations of towns elements in the ArrayList.
Then you want to sum all the elements in each combination and find the smallest difference between the sum and miles.
I found the following code for finding all possible combinations of n elements in an array. Hence I used an array of int rather than an ArrayList. Refer to Print all possible combinations of r elements in a given array of size n. I copied the code from that Web page and modified it so that it solves your problem. Note that I used your sample list and value for towns. Explanations of the code appear after it.
Also note that the comments in the code are from the original code that I copied.
public class TownsKms {
private static int counter;
private static int kms;
private static int min = Integer.MAX_VALUE;
private static int[] minArr;
/* arr[] ---> Input Array
data[] ---> Temporary array to store current combination
start & end ---> Staring and Ending indexes in arr[]
index ---> Current index in data[]
r ---> Size of a combination to be printed */
static void combinationUtil(int arr[],
int data[],
int start,
int end,
int index,
int r) {
// Current combination is ready to be printed, print it
if (index == r) {
int sum = 0;
for (int j=0; j<r; j++) {
sum += data[j];
}
int diff = Math.abs(kms - sum);
if (diff < min) {
min = diff;
System.arraycopy(data, 0, minArr, 0, minArr.length);
}
return;
}
// replace index with all possible elements. The condition
// "end-i+1 >= r-index" makes sure that including one element
// at index will make a combination with remaining elements
// at remaining positions
for (int i=start; i<=end && end-i+1 >= r-index; i++) {
data[index] = arr[i];
combinationUtil(arr, data, i+1, end, index+1, r);
}
}
// The main function that prints all combinations of size r
// in arr[] of size n. This function mainly uses combinationUtil()
static void printCombination(int arr[], int n, int r) {
// A temporary array to store all combination one by one
int data[]=new int[r];
// Print all combination using temprary array 'data[]'
combinationUtil(arr, data, 0, n-1, 0, r);
}
/**
* Start here.
*/
public static void main(String[] args) {
int arr[] = {91, 74, 73, 85, 73, 81, 87};
int towns = 4;
minArr = new int[towns];
kms = 331;
int n = arr.length;
printCombination(arr, n, towns);
int sum = 0;
boolean first = true;
for (int i = 0; i < minArr.length; i++) {
if (first) {
first = false;
}
else {
System.out.print(", ");
}
sum += minArr[i];
System.out.print(minArr[i]);
}
System.out.println(" = " + sum);
}
}
Rather than add more parameters to the methods, I decided to use class members instead. Also, rather than miles, I named the variable kms, i.e. kilometers.
The difference between the sum of the elements in a given combination and the value of kms may be negative. You want the difference that is closest to zero. Hence I calculate the absolute difference which is why I call method abs() of class Math.
The only thing that is unclear from your question is whether the size of a combination must be precisely the value of towns or can it be any size from one up to towns. In other words, if towns equals 4, do you want all combinations of 4 elements from the list or do you also want to check combinations of 1, 2 and 3 elements as well? If the latter, then you need to repeat the above code and each time change the value of towns, i.e. set towns = 1 and run the above code. Then set towns = 2, etc. But remember not to reset min.

Java min heap decrease array size after removing element

I am creating a priority queue (my own in array form) with a minimum heap sort where I am implementing a method which deletes the first element in the priority queue (my array) which is the root. I then call the heapifyNumbers() method on my array again to sort the array in minimum heap again. The problem is just that I cannot decrease from an array, so the last two elements will be duplicate.
This is the delete method I am creating
public void deleteMinimum(int[] array){
array[0] = array[array.length - 1];
heapSort(array);
//here I want to decrease array size by 1 after heap sorting the array
}
Here I just replace the first index with the last index, and then call the heapifyNumbers() method on my array again to sort the array. How do I decrease the array size by 1?
I know arrays cannot be decreased, but I see all implementations of this using arrays so there must be some way like creating a new array maybe?
This is my output:
Before Heap Sort :
[1, 10, 16, 19, 3, 5]
After Heap Sort :
[1, 3, 5, 10, 16, 19]
After deleting :
Here there are duplicate 19
[3, 5, 10, 16, 19, 19]
I have done this arr = Arrays.copyOf(array, array.length -1); but I don't know if it still holds the Log N time complexity
This is my full code if you are interested:
import java.util.*;
public class ObligatoriskOpgave2 {
int[] arr={1,10,16,19,3,5};
public static void buildheap(int []arr) {
/*
* As last non leaf node will be at (arr.length-1)/2
* so we will start from this location for heapifying the elements
* */
for(int i=(arr.length-1)/2; i>=0; i--){
heapifyNumbers(arr,i,arr.length-1);
}
}
public static void heapifyNumbers(int[] arr, int i, int size) {
int left = 2*i+1;
int right = 2*i+2;
int max;
if(left <= size && arr[left] > arr[i]){
max=left;
} else {
max=i;
}
if(right <= size && arr[right] > arr[max]) {
max=right;
}
// If max is not current node, swapCurrentNodeWithMaximumOfChildren it with max of left and right child
if(max!=i) {
swapCurrentNodeWithMaximumOfChildren(arr,i, max);
heapifyNumbers(arr, max,size);
}
}
public static void swapCurrentNodeWithMaximumOfChildren(int[] arr, int i, int j) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
public static int[] heapSort(int[] arr) {
buildheap(arr);
int sizeOfHeap=arr.length-1;
for(int i=sizeOfHeap; i>0; i--) {
swapCurrentNodeWithMaximumOfChildren(arr,0, i);
sizeOfHeap=sizeOfHeap-1;
heapifyNumbers(arr, 0,sizeOfHeap);
}
return arr;
}
public void deleteMinimum(int[] array){
array[0] = array[array.length - 1];
heapSort(array);
}
public static void main(String[] args) {
ObligatoriskOpgave2 o = new ObligatoriskOpgave2();
System.out.println("Before Heap Sort : ");
System.out.println(Arrays.toString(o.arr));
o.arr=heapSort(o.arr);
System.out.println("=====================");
System.out.println("After Heap Sort : ");
System.out.println(Arrays.toString(o.arr));
o.deleteMinimum(o.arr);
System.out.println(Arrays.toString(o.arr));
}
}
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
So if you want use array, you must create new array with your new length.
And fill new array with value of old array. (see part Copying Arrays in first link)
The solution was to have a HeapSize int value, which is decreased for each time an element is removed. Next time the array is iterated in a for loop, we don't go further than the heapsize.

How to copy only certain elements of one Array to another in Java

I am struggling to create an array with the correct size according to my parameters I have set up. Long story short this program is dealing with a set number of elements in the first array. Those elements are as follows
int [] myWeights = {258, 58, 209, 91, 79, 182, 172, 27, 7, 29, 128, 198};
Now those elements are in ounces. I get the program to run everything correctly, now my professor wants us to separate the ones that are over 8 pounds into a new array. Those elements in the new array in this case are 258, 209, 182, 172, and 198. The problem is that the program, at the beginning, can create a randomly sized array with varying sized elements between the numbers 1-320. Is there a way to have some sort of loop instantiate the proper amount of "boxes" needed. Or am I just supposed to instantiate some arbitrary number and hope that is what I will need? My current code for this is
public static int [] overGivenPounds(int x, int [] array){
int pounds = 0;
int arrayLength = 0;
int arrayOverEightPounds[];
int k = 0;
for(int i = 0; i < array.length; i++){
pounds = array[i] / 16;
if(x < pounds){
arrayOverEightPounds[k] = array[i];
k++;
}
}
return arrayOverEightPounds;
If any of this seems unclear please ask, there is no need to be rude. I am very new to Java.
Use a loop to determine the size of the target array
Create the target array of the needed size
Use a second loop to put values in the target array
Without that first step, you cannot know the right size of the array. If you create an array that's even one element too small or one element two big, that will be a waste,
because you will be forced to create a 3rd array to return an array of the right size.
So your solution should look something like:
public static int[] overGivenPounds(int x, int[] array) {
int size = 0;
for (int value : array) {
if (satisfies(x, value)) {
size++;
}
}
int[] result = new int[size];
// ??? -> for you to complete this
for (int value : array) {
if (satisfies(x, value)) {
// ??? -> for you to complete this
}
}
return result;
}
public static int[] overGivenPounds(int x, int[] array){
Arrays.sort(array);
boolean foundSomething = false;
int startIndex = 0;
for (int i = 0; i < array.length; i++) {
if(array[i]/16>=x){
startIndex = i;
foundSomething = true;
break;
}
}
if(foundSomething)
return Arrays.copyOfRange(array, startIndex, array.length);
return null;
}
Are you allowed to use Java streams? If so, the solution would be:
return Arrays.stream(myWeights).filter(n -> n/16 > x).toArray();
If not then you could use Arrays.copyOfto create an array of the correct length:
int[] heavyWeights = int[myWeights.length];
int size = 0;
for (int weight: myWeights)
if (weight / 16 > x)
heavyWeights[size++] = weight;
return Arrays.copyOf(heavyWeights, size);
Are you allowed to use other classes? If so, you could just use an ArrayList and then use
//int arrayOverEightPounds[];
List<Integer> listOverEightPounds = new ArrayList<>();
//...
//arrayOverEightPounds[k] = array[i];
listOverEightPounds.add(array[i]);
//....
return listOverEightPounds.toArray(new Integer[0]);
to return an array of the proper size. In this case you can get rid of k. ArrayList uses an array internally but will resize it automatically if it needs more space so you don't have to do that micro-management. The toArray method on ArrayList will return a new array of the proper size if the array that's passed in is not big enough. A common thing you see is to just pass in an array of size 0 into toArray which means the returned value will always be the correctly sized array.
The usual way to do it is to create an array that you know can hold everything, add your items to that array, while keeping track of how many items you have added. At the end you return a copy of the array, truncated to the number of items.
Or, with Java 8, you can write it as a stream one-liner:
return Arrays.stream(array).filter(i -> (i / 16) > x).toArray();

Categories