I am working on a program that uses quick sort to sort an array to display the running time. This program selects the median of three random numbers as the pivot. However, I am not sure if I am doing something wrong because every time I run this program I get the following errors:
"java.lang.StackOverflowError",
at java.util.Random.nextInt(Unknown Source)
at SortingItems.quickSort(SortingItems.java:31)
at SortingItems.quickSort(SortingItems.java:69) " I get this specific message multiple times"
This is the code:
import java.util.Random;
public class SortingItems {
static int x = 1000;
static int array [] = new int[x];
public static void main(String[] args) {
long time;
input(x, array);
time = System.nanoTime();
sort(array);
System.out.println("Running time in ascending order " + (System.nanoTime() - time));
}
public static void sort(int[] array) {
quickSort(array, 0, array.length - 1);
}
public static void quickSort(int[] array, int low, int high) {
if (array == null || array.length == 0)
return;
if (low >= high)
return;
// Generating random numbers from 0 to the last element of the array
Random f = new Random();
int first = f.nextInt(array.length - 1);
Random s = new Random();
int second = s.nextInt(array.length - 1);
Random t = new Random();
int third = t.nextInt(array.length - 1);
// Selecting the pivot
int pivot = Math.max(Math.min(array[first], array[second]),
Math.min(Math.max(array[first],array[second]), array[third]));
int i = low;
int j = high;
while (i <= j) {
while (array[i] < pivot) {
i++;
}
while (array[j] > pivot) {
j--;
}
if (i <= j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
}
if (low < j)
quickSort(array, low, j);
if (high > i)
quickSort(array, i, high);
}
// Input in ascending order
public static int[] input(int x, int[] array) {
for (int k = 0; k < x; k++) {
array[k] = k;
}
return array;
}
}
The problem seems to be with how the median is being selected here. The pivots should be chosen from between the current high and low positions and not the entire array.
Note that your test-input is in ascending order. Now, as you select three random values from the entire array of size 1000 for pivoting, when it comes to the smaller recursive cases, the arrays tend to be lopsided with a very high probability. This means that another level of recursion would be called with the same input parameters. In the long run, this is likely to cause a stack overflow with a high probability.
The following change should fix your issue:
// Generating random numbers from low to high
Random f = new Random();
int first = f.nextInt(high-low) + low;
Random s = new Random();
int second = s.nextInt(high-low) + low;
Random t = new Random();
int third = t.nextInt(high-low) + low;
Related
I tried to implement merge sort in Java using the code below. The mergeSort() method is supposed to be a recursive method that repeatedly divides the array into smaller sections, while the merge() method takes 2 sections of the array that has already been sorted and merges them into a single sorted section.
Here's the code:
class MergeSort{
public static void mergeSort(int[] array){
mergeSort(array, 0, array.length-1);
}
public static void mergeSort(int[] array, int start, int end){
int mid = (start + end)/2;
if (end > start) {
mergeSort(array, start, mid);
mergeSort(array, mid + 1, end);
merge(array, start, end, mid + 1);
}
}
public static void merge(int[] array, int start, int end, int mid){
int length = end - start + 1,length1 = mid- start, length2 = end - mid + 1, index1 = start, index2 = mid, sortedindex = 0;
boolean cont = true;
int[] sortedArray = new int[length];
while (cont){
if (array[index1] > array[index2]){
sortedArray[sortedindex] = array[index2];
index2++;
} else{
sortedArray[sortedindex] = array[index1];
index1++;
}
sortedindex++;
//reached the end of one array, dump the rest of the remaining array in the sorted array
if (index1 >= length1){
for (index2 = index2; index2 < length2; index2++){
sortedArray[sortedindex] = array[index2];
sortedindex++;
}
cont = false;
} else if (index2 >= length2){
for (index1 =index1; index1 < length1; index1++){
sortedArray[sortedindex] = array[index1];
sortedindex++;
}
cont = false;
}
}
//copy the sorted array into the main array
for (int i = 0; i <= length - 1; i++){
array[start+i] = sortedArray[i];
}
}
}
public class Main {
public static void main(String[] args) {
// write your code here
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\n");
Random random = new Random();
int length = scanner.nextInt();
int[] array = new int[length];
for (int i = 0; i < length;i++){
array[i] = random.nextInt(5000);
//System.out.println(array[i]);
}
MergeSort.mergeSort(array);
for (int i: array){
System.out.println(i);
}
}
}
The main class then generates an array with a user-defined length, populates it with random integers, and passes it to mergeSort().
Unfortunately the program outputs an array where the first few elements are sorted correctly, but the rest are zeros. e.g. given a randomly generated array {3291, 2879, 3078, 3609, 3534, 3922, 2793, 1098, 472, 1800}, the program outputs {472, 2879, 3291, 0, 0, 0, 0, 0, 0, 0}, with the number of correctly sorted elements in the output differing from run to run.
I can't seem to figure out what's wrong with my code. Any help would be greatly appreciated :)
while loop should close earlier.
public static void merge1(int[] array, int start, int end, int mid) {
int length = end - start + 1;
int[] sortedArray = new int[length];
int index1 = start;
int index2 = mid + 1;
int sortedindex = 0;
while (index1 <= mid && index2 <= end) {
if (array[index1] < array[index2]) {
sortedArray[sortedindex++] = array[index1++];
} else {
sortedArray[sortedindex++] = array[index2++];
}
}
// reached the end of one array, dump the rest of the remaining array in the
// sorted array
while (index1 <= mid) {
sortedArray[sortedindex++] = array[index1++];
}
while (index2 <= end) {
sortedArray[sortedindex++] = array[index2++];
}
// copy the sorted array into the main array
for (int i = 0; i <= length - 1; i++) {
array[start + i] = sortedArray[i];
}
}
I have two implementation of quick sort the first one uses a median of (fist ,middle , last ) as pivot and the second uses the middle element as pivot
the first Implementation :
public class quickMedian {
public void sort(int array[])
// pre: array is full, all elements are non-null integers
// post: the array is sorted in ascending order
{
quickSort(array, 0, array.length - 1); // quicksort all the elements in the array
}
public void quickSort(int array[], int start, int end)
{
int i = start; // index of left-to-right scan
int k = end; // index of right-to-left scan
if (end - start >= 1) // check that there are at least two elements to sort
{
if (array[start+(end-start)/2]>array[end]){
swap(array,start+(end-start)/2, end);
}
if (array[start]>array[end]){
swap(array,start, end);
}
if (array[start+(end-start)/2]>array[start]){
swap(array, start+(end-start)/2, start);
}
int pivot = array[start]; // set the pivot as the first element in the partition
while (k > i) // while the scan indices from left and right have not met,
{
while (array[i] <= pivot && i <= end && k > i) // from the left, look for the first
i++; // element greater than the pivot
while (array[k] > pivot && k >= start && k >= i) // from the right, look for the first
k--; // element not greater than the pivot
if (k > i) // if the left seekindex is still smaller than
swap(array, i, k); // the right index, swap the corresponding elements
}
swap(array, start, k); // after the indices have crossed, swap the last element in // the left partition with the pivot
quickSort(array, start, k - 1); // quicksort the left partition
quickSort(array, k + 1, end); // quicksort the right partition
}
else // if there is only one element in the partition, do not do any sorting
{
return; // the array is sorted, so exit
}
}
public void swap(int array[], int index1, int index2)
// pre: array is full and index1, index2 < array.length
// post: the values at indices 1 and 2 have been swapped
{
int temp = array[index1]; // store the first value in a temp
array[index1] = array[index2]; // copy the value of the second into the first
array[index2] = temp; // copy the value of the temp into the second
}
}
The second Implementation :
public class quickSort {
private int array[];
private int length;
public void sort(int[] inputArr) {
if (inputArr == null || inputArr.length == 0) {
return;
}
this.array = inputArr;
length = inputArr.length;
quickSorter(0, length - 1);
}
private void quickSorter(int lowerIndex, int higherIndex) {
int i = lowerIndex;
int j = higherIndex;
// calculate pivot number, I am taking pivot as middle index number
int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2];
// Divide into two arrays
while (i <= j) {
/**
* In each iteration, we will identify a number from left side which
* is greater then the pivot value, and also we will identify a number
* from right side which is less then the pivot value. Once the search
* is done, then we exchange both numbers.
*/
while (array[i] < pivot) {
i++;
}
while (array[j] > pivot) {
j--;
}
if (i <= j) {
exchangeNumbers(i, j);
//move index to next position on both sides
i++;
j--;
}
}
// call quickSort() method recursively
if (lowerIndex < j)
quickSorter(lowerIndex, j);
if (i < higherIndex)
quickSorter(i, higherIndex);
}
private void exchangeNumbers(int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
To obtain the median we need to do extra steps on each recursion which may increase the time a little bit (if the array is totally random) .
I am testing these two classes on an array of size N=10,000,000 randomly generated and I have done the test many times the first Implementation takes around 30 seconds and the second takes around 4 seconds
so this is obviously not caused by the extra overhead to get the median of three numbers .
There must be something wrong with the first implementation, what is it ?
here is the testing code :
public static void main(String[] args) {
File number = new File ("f.txt");
final int size = 10000000;
try{
// quickSort s = new quickSort();
quickMedian s = new quickMedian();
writeTofile(number, size);
int [] arr1 =readFromFile(number, size);
long a=System.currentTimeMillis();
s.sort(arr1);
long b=System.currentTimeMillis();
System.out.println("quickSort: "+(double)(b-a)/1000);
}catch (Exception ex){ex.printStackTrace();}
}
I'm trying to count minimum swaps(only consecutive swaps) in an array sorted by mergesort. It works for some cases but this case doesn't work for example: http://puu.sh/kC9mg/65e055807f.png. The first number is how many numbers it should sort, then you enter the numbers. In that case it should print 1 because the number of minimum consecutive swaps is 1 in this case which will swap 4 and 3.
This is the code I have:
public class MergeSort {
private int[] numbers;
private int[] helper;
private int number;
private long swapCounter = 0;
public MergeSort(int[] inputNumbers)
{
numbers = inputNumbers;
number = inputNumbers.length;
helper = new int[number];
mergesort(0, number-1);
}
private void mergesort(int low, int high) {
// check if low is smaller then high, if not then the array is sorted
if (low < high) {
// Get the index of the element which is in the middle
int middle = low + (high - low) / 2;
// Sort the left side of the array
mergesort(low, middle);
// Sort the right side of the array
mergesort(middle + 1, high);
// Combine them both
merge(low, middle, high);
}
}
private void merge(int low, int middle, int high) { // Merge it
long internCounter = 0;
for (int i = low; i <= high; i++) { // Copy both parts into the helper array
helper[i] = numbers[i];
}
int i = low;
int j = middle + 1;
int k = low;
while (i <= middle && j <= high) { // Copy the smallest values from either the left or the right side back to the original array
if (helper[i] < helper[j]) {
numbers[k] = helper[i];
i++;
internCounter++;
} else {
numbers[k] = helper[j];
j++;
swapCounter += internCounter;
}
k++;
}
while (i <= middle) { // Copy the rest of the left side of the array into the target array
numbers[k] = helper[i];
k++;
i++;
swapCounter += internCounter;
}
}
public long getCounter() // Get the counter
{
return this.swapCounter;
}
}
And this is my main class:
import java.util.Scanner;
public class Fr {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int numberOfStudents;
int[] inputNumbers2;
numberOfStudents = input.nextInt();
inputNumbers2 = new int[numberOfStudents];
for(int i = 0; i < numberOfStudents; i++)
{
inputNumbers2[i] = input.nextInt();
}
MergeSort ms = new MergeSort(inputNumbers2);
System.out.println(ms.getCounter());
input.close();
}
}
Do anyone have any thoughts what could be wrong?
I don't think you need the intern counter at all. Just count how many positions you swap an element when taking an element from the high half:
public class MergeSort {
private int[] numbers;
private int[] helper;
private int number;
private long swapCounter = 0;
public MergeSort(int[] inputNumbers)
{
numbers = inputNumbers;
number = inputNumbers.length;
helper = new int[number];
mergesort(0, number-1);
}
private void mergesort(int low, int high) {
// check if low is smaller then high, if not then the array is sorted
if (low < high) {
// Get the index of the element which is in the middle
int middle = low + (high - low) / 2;
// Sort the left side of the array
mergesort(low, middle);
// Sort the right side of the array
mergesort(middle + 1, high);
// Combine them both
merge(low, middle, high);
}
}
private void merge(int low, int middle, int high) { // Merge it
for (int i = low; i <= high; i++) { // Copy both parts into the helper array
helper[i] = numbers[i];
}
int i = low;
int j = middle + 1;
int k = low;
while (i <= middle && j <= high) { // Copy the smallest values from either the left or the right side back to the original array
if (helper[i] < helper[j]) {
numbers[k] = helper[i];
i++;
} else {
numbers[k] = helper[j];
swapCounter += (j-k);
j++;
}
k++;
}
while (i <= middle) { // Copy the rest of the left side of the array into the target array
numbers[k] = helper[i];
k++;
i++;
}
}
public long getCounter() // Get the counter
{
return this.swapCounter;
}
}
public int thirdLargest(int[] arr){
int f_l = arr[0];
int s_l = arr[0];
int t_l = arr[0];
for(int i=1;i<arr.length;i++)
{
if (f_l < arr[i]){
t_l = s_l;
s_l = f_l;
f_l = arr[i];
}
else if (s_l < arr[i]){
t_l = s_l;
s_l = arr[i];
}
else if (t_l < arr[i]){
t_l = arr[i];
}
}
return t_l;
}
my code didn't passes some cases,any suggestion?
parameter {24,27,30,31,34,37,40,42}' , passes
parameter {2,-1,-2,-3,-4,-5}' , fails
This is simply cause by the fact that you initialize all values to arr[0]. If all elements are smaller than arr[0] this code won't update the values, even though the second-largest element for example wouldn't be arr[0]. Instead initialize the variables for the third/second/largest value with Integer.MIN_VALUE and start the search with the first element (index = 0) instead of the second.
There is actually a well-known algorithm for this, which is more generic than yours. It is called quick-select and looks like a quick sort with an optimization making it faster (linear time in average) : since we don't need to sort the array, we just recurse on the part of the array containing the index we are looking for (in your case, third item so index 2).
Here is an implementation in Java :
private static final Random rd = new Random();
public static int kthElement(int[] arr, int k) {
return kthElement(arr,k,0,arr.length);
}
private static T kthElement(int[] arr, int k, int min, int max) {
if (min < max - 1) {
int p = pivot(arr,min,max);
return p == k - 1 ? arr[p] :
p < k - 1 ? kthElement(arr,k,p + 1,max) : kthElement(arr,k,min,p);
}
return arr[min];
}
private static int pivot(int[] arr, int min, int max) {
int pivot = min + rd.nextInt(max - min);
swap(arr,pivot,max - 1);
pivot = min;
for (int i=min ; i<max ; i++)
if (arr[i] < arr[max - 1]) swap(arr,i,pivot++);
swap(arr,max - 1,pivot);
return pivot;
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
Well, as an alternative to your working code, here is a solution that will allow you to find the Nth largest integer in your array using Collections to do the heavy lifting:
import java.util.Arrays;
import java.util.Collections;
public class ArrayNthLargest {
public static int getNthLargest(int[] arrayInput, int n) {
Integer[] sortedArray = new Integer[arrayInput.length];
for (int i = 0; i < arrayInput.length; i++) {
sortedArray[i] = new Integer(arrayInput[i]);
}
Arrays.sort(sortedArray, Collections.reverseOrder());
return (sortedArray[n - 1]);
}
public static void main(String[] args){
int nth = new Integer(0);
int n = new Integer(3);
int[] testArray = {1,2,3,4,5,6,23,44,55,8,1};
nth = getNthLargest(testArray, n);
System.out.printf("The %d sorted array value is %d", n, nth);
}
}
This was actually an interesting question to me to do in O(n) complexity. I hope this solution is order n. I used an ArrayList as a stack (since Stack object won't allow addition of items in specific incidences (I've generalized it).
public int thirdLargest(int[] arr){
public int N_TH = 3; // Assuming this is nth largest you want
public ArrayList<Integer> largest = new ArrayList<Integer>(N_TH);
for(int i = 0;i<N_TH;i++)
largest.add(0); // initialize the ArrayList
for(int i = 0;i<arr.length;i++) {
for(int j=0;j<largest.size();j++){
if(arr[i] >= largest.get(j)) {
// Add the item at the correct index
// Pop the last element
largest.remove(largest.size()-1);
largest.add(j,arr[i]);
break;
}
}
}
return largest.get(N_TH);
}
Let me know if you find any problems with it, I might have mistyped part of trying to put it in OP's method.
EDIT won't work with negative numbers at the moment. You can find the smallest value in arr and initialize largest with that value. Then it'll also with negative numbers
I am wondering why my code keeps having this "time limit exceed" on the uva-online judge page (http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2511), it is supposed to execute in 1 second but I don't know which input they use (my code works and do exactly what it supposed).. I am wondering that maybe the while loop of the testCases have something to do, because when I remove it it says wrong answer.. this is my code:
public class Main {
private static final int TAM = 10000; // TAM equals to the posible numbers of houses
private static int[] auxHouses;
private static int nHouses[];
private static int testCases;
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
nHouses = new int[TAM];
// First we read the input
// Read the variable of testCases
testCases = scanner.nextInt();
while (testCases > 0) {
float sol = binarySearch(testCases);
System.out.println(sol);
testCases--;
}
}
public static float binarySearch(int tC) {
int routers = 0, houses = 0;
int pivot = 0;
int hi = 0;
// While for the testCases
routers = scanner.nextInt();
houses = scanner.nextInt();
// Read the numbers of the houses
for (int i = 0; i < houses; i++) {
nHouses[i] = scanner.nextInt();
}
if (routers >= houses) {
return 0;
}
// First we sort the array
sortHouses(nHouses, houses);
// Prepare the variables of the index
int lo = 0;
hi = 2 * (nHouses[houses - 1] - nHouses[0] + 1); // 2*(loc[h-1]-loc[0]+1);
// Now we execute the binary search algorithm
while (hi > lo) {
pivot = (lo + hi) / 2;
int start = nHouses[0];
int need = 1;
for (int i = 0; i < houses; i++) {
if (nHouses[i] > start + pivot) {
start = nHouses[i];
need++;
}
}
if (need > routers) {
lo = pivot + 1;
} else {
hi = pivot;
}
}
return (float) hi / 2;
}
public static void sortHouses(int[] nhouses, int length) {
// First we check if the are actually values on the array
if (nhouses.length == 0) {
return;
}
// Copy the array of int into an auxiliary variable and the numbers of
// int in the array
auxHouses = nhouses;
int lengthArray = length;
quickSort(0, lengthArray - 1);
}
public static void quickSort(int low, int high) {
// System.out.println("Array " + Arrays.toString(auxHouses));
int i = low, j = high;
// Get the pivot element from the middle of the list
int pivot = auxHouses[low + (high - low) / 2];
// Divide into two lists
while (i <= j) {
// If the current value from the left list is smaller then the pivot
// element then get the next element from the left list
while (auxHouses[i] < pivot) {
i++;
}
// If the current value from the right list is larger then the pivot
// element then get the next element from the right list
while (auxHouses[j] > pivot) {
j--;
}
// If we have found a values in the left list which is larger then
// the pivot element and if we have found a value in the right list
// which is smaller then the pivot element then we exchange the
// values.
// As we are done we can increase i and j
if (i <= j) {
exchange(i, j);
i++;
j--;
}
}
// Recursion
if (low < j)
quickSort(low, j);
if (i < high)
quickSort(i, high);
}
private static void exchange(int i, int j) {
int temp = auxHouses[i];
auxHouses[i] = auxHouses[j];
auxHouses[j] = temp;
}
}
I have it with the quicksort implemented, but if you use Arrays.sort(..) method instead it says the same thing..TLE, what could be doing wrong?