I am giving a time interval in the form of two arrays.
A[0]= 2 B[0]=3
A[1]= 9 B[1]=11
A[2] = 5 B[2]=6
A[3] = 3 B[3]=10
I want to sort the interval on the basics of starting time i.e.
(2,3) , (3,10) ,(5,6) ,(9,11)
Does i have to make a structure of this. or it can be done straight.
Try:
private static class StartEnd implements Comparable<StartEnd> {
private final int start;
private final int end;
// + constructor + getters
#Override
public int compareTo(StartEnd other) {
return start - other.getStart();
}
}
public void sort(int[] starts, int[] ends) {
StartEnd[] ses = new StartEnd[starts.length];
for(int i = 0 ; i < starts.length ; ++i) {
ses[i] = new StartEnd(starts[i], ends[i]);
}
Arrays.sort(sis);
// re-insert
for(int i = 0 ; i < ses.length ; ++i) {
starts[i] = ses[i].getStart;
ends[i] = ses[i].getEnd();
}
}
It can be done straight, since you dont show what have you tried so far I just give you the algorithm:
for j = 1 to n
for i = i+1 to n
if(A[i]>A[j]){
swap(A[i],A[j])
swap(B[i],B[j])
}
you can easily convert it to java code.
this algorithm is buble sort if you want better algorithm use this wiki link to improve your time.
As DwB want here is merge sort full java code that do what you want. I got merge sort algorithm from here and modify to satisfy your need. also you could see the working version on Ideone
Merge Sort:
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
private int[] A;
private int[] B;
private int[] helperA;
private int[] helperB;
private int length;
public static void main (String[] args){
int[] As = {2,9,5,3};
int[] Bs = {3,11,6,10};
new Ideone().sort(As,Bs);
}
public void sort(int[] As , int[] Bs) {
A = As;
B = Bs;
length = A.length;
this.helperA = new int[length];
this.helperB = new int[length];
mergesort(0, length - 1);
for(int i = 0 ; i<length ; i++)
System.out.println("(" + A[i] + "," + B[i]+ ")");
}
private void mergesort(int low, int high) {
// check if low issmaller 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) {
// Copy both parts into the helper array
for (int i = low; i <= high; i++) {
helperA[i] = A[i];
helperB[i] = B[i];
}
int i = low;
int j = middle + 1;
int k = low;
// Copy the smallest values from either the left or the right side back
// to the original array
while (i <= middle && j <= high) {
if (helperA[i] <= helperA[j]) {
A[k] = helperA[i];
B[k] = helperB[i];
i++;
} else {
A[k] = helperA[j];
B[k] = helperB[j];
j++;
}
k++;
}
// Copy the rest of the left side of the array into the target array
while (i <= middle) {
A[k] = helperA[i];
B[k] = helperB[i];
k++;
i++;
}
}
}
Step 1: Java is an object oriented language; learn to use objects.
Possible class for the time interval
public class TimeInterval implements Comparable<TimeInterval>
{
private int end;
private int start;
public TimeInterval(
final int end,
final int start)
{
this.end = end;
this.start = start;
}
public int getEnd()
{
return end;
}
public int getStart()
{
return start;
}
public int comareTo(final TimeInterval other)
{
if (other == null)
{
return -1; // this will put the null value objects at the end.
}
return start - other.start;
}
}
The classical Javanese "object oriented" approach for this is to use a dedicated class storing a pair of values (int values, in this case), and sort them, as already pointed out in most of the other answers. However, I'd recommend to not make this class Comparable. Instead, a Comparator could be used, which would make it much easier to introduce new sorting orders. Particularly, there could be Comparator implementations for sorting in ascending/descending order, based on the first/second value, respectively. Only then, object orientation plays out its advantages, compensating the "disadvantage" of having to create such a pair of int values as a "dummy data structure" in the first place...
However, I wanted to try to find a solution for the original question as well, namely, sorting two arrays "in sync". Despite the task of sorting seemingly being trivial, one can dedicate a lot of work to doing it right (see Chapter 3 of TAOCP). A bubble sort is simple but inefficient even for medium-sized arrays. Implementing a quick- or merge sort can be fiddly when trying to get the indices right. However, one solution can be obtained by simply taking the existing sort method from java.lang.Arrays, and factoring out the most elementary building block: The swap function:
public class ArraySort
{
public static void main(String[] args)
{
final int A[] = new int[4];
final int B[] = new int[4];
A[0] = 2; B[0] = 3;
A[1] = 9; B[1] = 11;
A[2] = 5; B[2] = 6;
A[3] = 3; B[3] = 10;
Swapper swapper = new Swapper()
{
#Override
public void swap(int array[], int i0, int i1)
{
ArraySort.swap(A, i0, i1);
ArraySort.swap(B, i0, i1);
}
};
sort(A, 0, A.length, swapper);
for (int i=0; i<A.length; i++)
{
System.out.println("("+A[i]+","+B[i]+")");
}
}
interface Swapper
{
void swap(int array[], int i0, int i1);
}
public static void swap(int array[], int i0, int i1)
{
int t = array[i0];
array[i0] = array[i1];
array[i1] = t;
}
// The following methods are copied from java.util.Arrays:
public static void sort(int x[], int off, int len, Swapper swapper)
{
if (len < 7)
{
for (int i = off; i < len + off; i++)
{
for (int j = i; j > off && x[j - 1] > x[j]; j--)
{
swapper.swap(x, j, j - 1);
}
}
return;
}
int m = off + (len >> 1);
if (len > 7)
{
int l = off;
int n = off + len - 1;
if (len > 40)
{
int s = len / 8;
l = med3(x, l, l + s, l + 2 * s);
m = med3(x, m - s, m, m + s);
n = med3(x, n - 2 * s, n - s, n);
}
m = med3(x, l, m, n);
}
int v = x[m];
int a = off, b = a, c = off + len - 1, d = c;
while (true)
{
while (b <= c && x[b] <= v)
{
if (x[b] == v)
{
swapper.swap(x, a++, b);
}
b++;
}
while (c >= b && x[c] >= v)
{
if (x[c] == v)
{
swapper.swap(x, c, d--);
}
c--;
}
if (b > c)
{
break;
}
swapper.swap(x, b++, c--);
}
int s, n = off + len;
s = Math.min(a - off, b - a);
vecswap(x, off, b - s, s, swapper);
s = Math.min(d - c, n - d - 1);
vecswap(x, b, n - s, s, swapper);
if ((s = b - a) > 1)
{
sort(x, off, s, swapper);
}
if ((s = d - c) > 1)
{
sort(x, n - s, s, swapper);
}
}
private static void vecswap(int x[], int a, int b, int n, Swapper swapper)
{
for (int i = 0; i < n; i++, a++, b++)
{
swapper.swap(x, a, b);
}
}
private static int med3(int x[], int a, int b, int c)
{
return (x[a] < x[b] ? (x[b] < x[c] ? b : x[a] < x[c] ? c : a)
: (x[b] > x[c] ? b : x[a] > x[c] ? c : a));
}
}
Notes
This is not a solution that I would recommend. It's just an attempt to answer the question
or it can be done straight. [sic!]
And the answer is: Yes, it is possible, although the solutions that are introducing some sort of an IntPair are more idiomatic.
Apart from that, it would probably be more efficient to "inline" the Swapper#swap calls to directly swap elements of two arrays that are stored in instance variables, or passed as method parameters. However, I liked the genericity of such a Swapper interface. Additionally, it would be nice to generalize this even further, by passing in something like a
interface IntArrayEntryComparator {
int compare(int array[], int i0, int i1);
}
But the latter would go beyond what I wanted to test/demonstrate with this class.
instead having two arrays, create object which holds your intervals
class Interval implements Comparable<Interval> {
private Long start,completed
public Interval(Long start, Long completed) {
this.start = start;
this.completed = completed;
}
#Override
public int compareTo(Interval o) {
return start.compareTo(o.start);
}
//getters and setters ommited
}
then, all what you need to do is implement compareTo method and put all your data in some collection ie List<Interval> intervals
and used Collections.sort(intervals) to sort them
EDIT
Example:
originally you have:
A[0]= 2 B[0]=3,
A[1]= 9 B[1]=11
A[2] = 5 B[2]=6
A[3] = 3 B[3]=10`
lets replace this by:
List<Interval> intervals = new ArrayList<>();
intervals.add(new Interval(2L,3L));
intervals.add(new Interval(9L,11L));
intervals.add(new Interval(5L,6L));
intervals.add(new Interval(3L,10L));
//NOTE L is added at the end variable as interval uses Long, if you change it to integer you dont need to add it;
And now all what you need to do is sort
Collection.sort(intervals);
Related
I've tried to write a Mergesort Algorithm in Java:
static void merge(int[] sort, int l, int m, int r) {
int[] cache_array = new int[r - l + 1];
int l_cache = l;
int _mid = m + 1;
for (int i = 0; i < r - l + 1; i++) {
if (l > m) {
cache_array[i] = sort[_mid];
_mid++;
} else { if (_mid > r) {
cache_array[i] = sort[l];
l++;
} else { if (sort[l] >= sort[_mid]) {
cache_array[i] = sort[l];
l++;
} else { if (sort[_mid] > sort[l]) {
cache_array[i] = sort[_mid];
_mid++;
}}}}
}
for (int i = 0; i < cache_array.length; i++) {
sort[i + l_cache] = cache_array[i];
}
}
static void mergeSort(int[] sort, int l, int r) {
if (l < r) {
int mid = (int)Math.floor((l + r - 1) / 2);
mergeSort(sort, l, mid);
mergeSort(sort, mid + 1, r);
merge(sort, l, mid, r);
}
}
public static void main(String[] args) {
int[] a = { 2, 1, 4, 5, 73, 74, 7, 5, 64, 2 };
mergeSort(a, 0, a.length - 1);
for (int i : a) {
System.out.println(i);
}
}
But it just sorts a part of the Array and replaces the rest of it with zeros. I tried to change the cache_array to a LinkedList but nothing changed and after I tried debugging I couldn't find out anything, too.
I'd appreciate it if you'd help me and/or show me another Mergesort Algorithm that works for Java.
(I used this Algorithm because it worked for Python and so I wanted to use similar code in Java)
The bug in your code is difficult to spot:
the loop in your merge function iterates for i from 0 to r - l + 1 excluded, which would be correct if r and l remained constant during the loop, but you increment l each time you copy from the left part, reducing the number of iterations. As a consequence, the loop exits early, leaving the remaining elements in cache_array with their default value 0.
There are multiple sources of confusion in the code:
the convention to include r in the slice is confusing: it requires +1/-1 adjustments to compute the slice lengths and the middle index.
using Math.floor() is useless: integer arithmetic uses integer division in java.
incrementing the l and m arguments is confusing as these lose their meaning if the value is changed. Use other index variables to iterate through the arrays.
adding a { between the else and if keywords introduces unnecessary indentation levels.
the last condition is the opposite of the previous one: you should just omit it. Note that if the array elements were floating point values, both conditions could be false for NaN values and some elements of cache_array would be left untouched. This last condition would cause errors in this case.
Here is a modified version:
// merge adjacent slices of the `sort` array.
// left slice has elements from `l` included to `m` excluded
// right slice has elements from `m` included to `r` excluded
static void merge(int[] sort, int l, int m, int r) {
int len = r - l;
int[] cache_array = new int[len];
for (int i = 0, ll = l, mm = m; i < len; i++) {
if (ll >= m) {
cache_array[i] = sort[mm];
mm++;
} else
if (mm >= r) {
cache_array[i] = sort[ll];
ll++;
} else
if (sort[ll] >= sort[mm]) {
cache_array[i] = sort[ll];
ll++;
} else {
cache_array[i] = sort[mm];
mm++;
}
}
for (int i = 0; i < len; i++) {
sort[l + i] = cache_array[i];
}
}
static void mergeSort(int[] sort, int l, int r) {
if (r - l > 1) {
int mid = l + (r - l) / 2;
mergeSort(sort, l, mid);
mergeSort(sort, mid, r);
merge(sort, l, mid, r);
}
}
public static void main(String[] args) {
int[] a = { 2, 1, 4, 5, 73, 74, 7, 5, 64, 2 };
mergeSort(a, 0, a.length);
for (int i : a) {
System.out.println(i);
}
}
This is how I write the mergesort algorithm.
public static int[] mergeSort(int[] sort) {
if(sort.length > 1) {
int mid = sort.length / 2;
int[] left = Arrays.copyOf(sort, mid);
int[] right = Arrays.copyOfRange(sort, mid, sort.length);
// sort the left and right arrays
mergeSort(left);
mergeSort(right);
// Merge the arrays
merge(sort, left, right);
}
}
private static void merge(int[] sort, int[] leftArray, int[] rightArray) {
// These values are just to keep track of our position in each of the 3
// arrays
int l = 0; // left array
int r = 0; // right array
int o = 0; // the actual array being sorted
while(l < leftArray.length && r < rightArray.length) {
if(leftArray[l] < righArray[r]) {
sort[o++] = leftArray[l++];
}
else {
sort[o++] = leftArray[r++];
}
}
// Now that we are out of the while loop we know that either the
// left or right array has all of its values in sort, so we just
// need to put the rest of the values in the array that doesn't have
// all of its elements in sort with the following code.
while(l < leftArray.length) {
sort[o++] = leftArray[l++];
}
while(r < rightArray.length) {
sort[o++] = rightArray[r++];
}
}
I usually implement it like this:
/// <summary>
/// Mergesort
/// best-case: O(n* log(n))
/// average-case: O(n* log(n))
/// worst-case: O(n* log(n))
/// </summary>
/// <returns>The sorted array.</returns>
/// <param name="array">array.</param>
public static int[] MergeSort(int[] array) {
// Exit condition for recursion
if (array.length <= 1) return array;
// Middle index of list to sort
int m = array.length / 2;
// Define left and right sub-listså
int[] left_array = new int[m];
int[] right_array = new int[array.length - m];
// Initialize left list
for (int i = 0; i < m; i++) left_array[i] = array[i];
// Initialize right list
for (int i = m, x = 0; i < array.length; i++, x++) right_array[x] = array[i];
// Recursively sort left half of the list
left_array = MergeSort(left_array);
// Recursively sort right half of the list
right_array = MergeSort(right_array);
// Merge sorted sub-lists
return Merge(left_array, right_array);
}
/// <summary>
/// Merge the specified left_array and right_array.
/// </summary>
/// <returns>The merge.</returns>
/// <param name="left_array">Left array.</param>
/// <param name="right_array">Right array.</param>
public static int[] Merge(int[] left_array, int[] right_array) {
int[] m = new int[left_array.length + right_array.length];
int index_l = 0;
int nl, nr;
nl = left_array.length - 1;
nr = right_array.length - 1;
for (int i = 0; i <= nl + nr + 1; i++) {
if (index_l > nl) {
m[i] = (right_array[i - index_l]);
continue;
}
if (index_l < i - nr) {
m[i] = (left_array[index_l]);
index_l++;
continue;
}
if (left_array[index_l] <= (right_array[i - index_l])) {
m[i] = (left_array[index_l]);
index_l++;
} else {
m[i] = (right_array[i - index_l]);
}
}
return m;
}
A few months ago I wrote all of the common sorting algorithms and this is what I got. A bit inaccurate but just to See how this implementation performs.
The other algorithms are here.
To achieve a descending order I think you just have to swap the comparison operators.
Dear fellow Stackoverflowers,
My swap method isn't working inside the insertionSort method; it is not swapping my array elements.
What's wrong with my insertion sort algorithm?
package AlgoExercises;
import java.util.Arrays;
public class InsertionSort {
static int[] numbersArray = { 5, 2, 4, 6, 1, 3 };
static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
static void insertionSort(int[] numbersArray) {
for (int i = 1; i < numbersArray.length - 1; i++) {
int j = i;
while ((j > 0) && (numbersArray[j] < numbersArray[j - 1])) {
swap(numbersArray[j], numbersArray[j - 1]);
j = j - 1;
System.out.println(Arrays.toString(numbersArray));
}
}
}
public static void main(String args[]) {
insertionSort(numbersArray);
}
}
Solution:
After fixing the swap method where int[] was included in its parameters, swap now works! I've also edited numbersArray.length-1 to numbersArray.length.
Thank you for your help guys!
package AlgoExercises;
import java.util.Arrays;
public class InsertionSort {
static int[] numbersArray = { 5, 2, 4, 6, 1, 3 };
static void swap(int i, int j) {
int temp = numbersArray[j];
numbersArray[j] = numbersArray[i];
numbersArray[i] = temp;
}
static void insertionSort(int[] numbersArray) {
for (int i = 1; i < numbersArray.length; i++) {
int j = i;
while ((j > 0) && (numbersArray[j] < numbersArray[j - 1])) {
swap(j, j - 1);
j = j - 1;
System.out.println(Arrays.toString(numbersArray));
}
}
}
public static void main(String args[]) {
insertionSort(numbersArray);
}
}
Java is a pass by value language, so swapping the int variables passed to the swap method makes no difference. You should pass the array itself + the two indices to swap to the method, and modify the array in the swap method.
static void swap(int[] arr, int i, int j) {
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
and call it
swap(numbersArray, j, j-1);
Note that I didn't check the logic of your insertion sort implementation. This answer only deals with the swap issue.
Just to give you another way of thinking why your existing swap method doesn't work: if you write code like this:
void swap(int a, int b) {
int t = a;
a = b;
b = t;
}
void callSwap() {
int x = 1;
int y = 2;
swap(x, y);
System.out.println(x + ", " + y);
}
You can 'inline' the swap method, basically copying it into the callSwap method. The semantically equivalent code would be:
void callSwap() {
int x = 1;
int y = 2;
// Start of inlined swap method.
{
int a = x;
int b = y;
int t = a;
a = b;
b = t;
}
// End of inlined swap method.
System.out.println(x + ", " + y);
}
Hopefully, you wouldn't expect x and y to have swapped values.
Note that this behaviour has nothing to do with the fact that the variable names a and b are different to x and y; I simply chose them to be different. Were the parameters of swap called x and y, it would be necessary to rename them to something else when inlining, since they are completely separate from the x and y in callSwap.
I've been banging my head on the table on this one.
I need to create an n sized array that is optimized for QuickSort Partition. It will be used to demonstrate the growth of QuickSort's best case. I know that for best case, QuickSort must select a pivot that divides the array in half for every recursive call.
I cannot think of a way to create an n-sized optimized array to test. Any help would be greatly appreciated.
Here is the algorithm in Java.
public class QuickSort {
private int length;
private void quickSort(int[] a, int p, int r) {
if (p < r) {
int q = partition(a, p, r);
quickSort(a, p, q - 1);
quickSort(a, q + 1, r);
}
}
private int partition(int[] a, int p, int r) {
int x = a[r];
int i = p - 1;
for (int j = p; j < r; j++) {
if (a[j] <= x) {
i++;
exchange(a, i, j);
}
}
exchange(a, i + 1, r);
return i + 1;
}
public void exchange(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
QuickSort(int[] a) {
if (a == null || a.length == 0) {
return;
}
length = a.length;
quickSort(a, 0, length - 1);
}
}
I know this is an old question, but I had the same question and finally developed a solution. I'm not a Java programmer, so don't blame me for Java code issues, please. I assumed that the quicksort algorithm always takes the first item as a pivot when partitioning.
public class QuickSortBestCase
{
public static void generate(int[] arr, int begin, int end)
{
int count = end - begin;
if(count < 3)
return;
//Find a middle element index
//This will be the pivot element for the part of the array [begin; end)
int middle = begin + (count - 1) / 2;
//Make the left part best-case first: [begin; middle)
generate(arr, begin, middle);
//Swap the pivot and the start element
swap(arr, begin, middle);
//Make the right part best-case, too: (middle; end)
generate(arr, ++middle, end);
}
private static void swap(int[] arr, int i, int j)
{
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
private static void fillArray(int[] arr)
{
for(int i = 0; i != arr.length; ++i)
arr[i] = i + 1;
}
private static void printArray(int[] arr)
{
for(int item : arr)
System.out.print(item + " ");
}
public static void main(String[] args)
{
if(args.length == 0)
return;
int intCount = Integer.parseInt(args[0]);
int[] arr = new int[intCount];
//We basically do what quicksort does in reverse
//1. Fill the array with sorted values from 1 to arr.length
fillArray(arr);
//2. Recursively generate the best-case array for quicksort
generate(arr, 0, arr.length);
printArray(arr);
}
}
This program produces the same output for the array of 15 items, as described here: An example of Best Case Scenario for Quick Sort. And in case someone needs a solution in C++:
template<typename RandomIterator,
typename Compare = std::less<typename RandomIterator::value_type>>
void generate_quicksort_best_case_sorted(RandomIterator begin, RandomIterator end)
{
auto count = std::distance(begin, end);
if (count < 3)
return;
auto middle_index = (count - 1) / 2;
auto middle = begin + middle_index;
//Make the left part best-case first
generate_quicksort_best_case_sorted(begin, middle);
//Swap the pivot and the start element
std::iter_swap(begin, middle);
//Make the right part best-case, too
generate_quicksort_best_case_sorted(++middle, end);
}
template<typename RandomIterator,
typename Compare = std::less<typename RandomIterator::value_type>>
void generate_quicksort_best_case(RandomIterator begin, RandomIterator end)
{
{
auto current = begin;
RandomIterator::value_type value = 1;
while (current != end)
*current++ = value++;
}
generate_quicksort_best_case_sorted(begin, end);
}
I've implemented the Heap's algorithm for finding all permutations of the elements of array A:
//A = {1, 2, 3, 4}; B = perms(A) ; num_row(B) = (4!+1) and B[0][0] = 4!;
//This is B.R. Heap's algorithm
public static void perms(int [] A, int [][]B, int n)
{
if (n == 1)
{
int k = B[0][0];
for (int i = 0; i < A.length; i++)
{
B[k + 1][i] = A[i];
}
B[0][0]++;
}
else
{
for (int i = 0; i < n - 1 ;i++)
{
perms(A, B, n-1);
if (n % 2 == 0)
{
swap(A, i, n - 1);
}
else
{
swap(A, 0, n - 1);
}
}
perms(A, B, n - 1);
}
}
public static void swap(int[] A, int i, int j)
{
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
I'm new to Java. The problem is I want to have B as the output (return) of the function perms(A) , but in this implementation, I have to initialize a int[n! + 1][A.length] B array before calling the function. How can I do it?
Is there anything like private variable or anything in java to help a recursive function to remember a variable from a former call?
Thanks
You can create an "entering" method to recursion like this:
public static int[][] perms(int[] a){
int[][] perms = new int[factorial(a.length)+1][a.length];
perms(a,perms,a.length);
return perms;
}
Method factorial is well know method and can be found on Google for example
Wondering if n parameter is neccessary
EDIT
it is not neccessary (above corrected)
EDIT
By my test the k variable is just incrementing, so I would use static variable like this:
private static int counter = 0;
// your code here, following is a part of your perms method
if (n == 1)
{
for (int i = 0; i < A.length; i++)
{
B[counter][i] = A[i];
}
counter++;
}
//and my code corrected too:
public static int[][] perms(int[] a){
int[][] perms = new int[factorial(a.length)][a.length]; //+1 is not necessary
counter=0; //necessary to call it again
perms(a,perms,a.length);
return perms;
}
Here is the code .. I have to sort an already sorted array and to calculate it's execution time ...for quicksort it is n^2 cause it is the worst case. but for large input data let's say 7500 it gives me an overflow error :S what can i do in order to calculate the running time?
public class Provo {
public static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static int HoarePartition(int m, int d, int[] a) {
int pivot = a[m];
int i = m + 1;
int j = d;
while (i < j) {
while (a[i] < pivot) {
i = i + 1;
}
while (a[j] > pivot) {
j = j - 1;
}
if (i < j)
swap(a, i, j);
}
swap(a, m, j);
return j;
}
public static void quicksort(int m, int d, int[] a) {
if (m < d) {
int s = HoarePartition(m, d, a);
quicksort(m, s - 1, a);
quicksort(s + 1, d, a);
}
}
}
and here is the main class
import javax.swing.*;
public class ascending {
public static void main(String[] args){
String input=JOptionPane.showInputDialog("Shkruani nr e te dhenave");
int size=new Integer(input).intValue();
int[] r= new int[size];
int[] p = new int[size];
int majtas=0;
int djathtas=size;
for(int i=majtas;i<djathtas;i++)
{r[i]=i;}
for(int i=majtas;i<djathtas;i++)
{p[i]=r[i];}
long average;
int n=100;
long result=0;
for(int j=1;j<=n;j++)
{
long startTime = System.nanoTime();
Provo.quicksort(majtas,djathtas-1,p);
long endTime = System.nanoTime();
result = result+(endTime-startTime);
long a = endTime-startTime;
System.out.println(j+": " +a);
for(int i=majtas;i<djathtas;i++)
{p[i]=r[i];}
}
average=result/n;
System.out.println("Koha e ekzekutimit te insertion sort eshte " + average + " nanosekonda ");
}
}
Well if you are stuck, you can maybe look for iterative quicksort on the web to get some help.
I have found this article. It is dedicated to C# but translating it into Java shouldn't be a big issue.
Change int djathtas = size - 1; to int djathtas = size; and change quicksort(majtas, djathtas, p); to quicksort(majtas, djathtas - 1, p);
Otherwise it's not allocating 10 digits, only 9.
It seems like you're just using too large of a number. Your program can be functioning correctly and generate a stack overflow error. You could try implementing another version of quicksort that does not rely on the stack or something.
Other than that, I'm not sure why you need such a large input anyway.