Fast way to check integer in the array. Array has not continuous integer in it, instead it has spatial numbers e.g. [1,4,11, 120,2,3].
In time efficient way, how do one check 3 in [212,31219,1,12,4]? Result is false
The answer depends on how often you need to check for a given integer.
If you have to check the same array over and over again it would be faster to sort it once and use a binary search algorithm to find your number (or not, if your number is not in the array).
In Java you don't have to reinvent the wheel. You can use the static methods in Arrays for these tasks (N size of your array):
Arrays.sort(...) will sort your array in ascending order. This sorts the array in O(N*log(N)) steps.
Arrays.binarySearch(...) afterwards will find your number in the sorted array. Finds your Element in O(log(N)) steps.
If you check for a given value only once in a while you may simply iterate over the array. Finds your Element in O(N) steps.
There are two approaches
Consider array of size N , and T searches
Linear search method
Complexity : O (T * N)
Sample code :
class Main {
public static void main(String[] args) {
int[] arr = { 212, 31219, 1, 12, 4 };
// perform searches from here
// for eg.
// boolean exists = contains(arr, 4);
}
public static boolean contains(int[] arr, int x) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == x) {
return true;
}
}
return false;
}
}
Binary search method
Complexity : O (N * log(N) + T * log(N)
Sample code :
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int[] arr = { 212, 31219, 1, 12, 4 };
// sort array first => complexity O(N * log(N))
Arrays.sort(arr);
// perform searches from here
// for eg.
// boolean exists = contains(arr, 2);
}
public static boolean contains(int[] arr, int key) {
return Arrays.binarySearch(arr, key) >= 0 ? true : false;
}
}
So if your number of searches is very high use binary search method else use linear search method.
Related
I'm trying to write a class named Range, that takes an array of integers (unsorted) of length n, containing only numbers in the range are from 0 to k.
At first, I declare a constructor which will preprocess the array via Counting Sort algorithm.
Then I want to write query() method that takes two integer arguments: a and b, which form a range of numbers from a to b and returns the total frequency of all the elements in the array having the values within the given range.
My code:
import java.util.Arrays;
import java.util.HashMap;
public class Range {
private int[] a;
private int k;
public Range(int[] a, int k) {
int index = 0;
int[] counterArray = new int[k + 1];
for (int i : a)
counterArray[i]++; // initialize counterArray
for (int i = 0; i < counterArray.length; i++)
while (0 < counterArray[i]) {
a[index++] = i;
counterArray[i]--;
} // end while()
this.a = a;
this.k = k;
} // end constructor()
public int query(int a, int b) {
HashMap<Integer, Integer> map = new HashMap<>(a);
} // end query()
#Override
public String toString() {
return Arrays.toString(a);
} // end toString()
}
I chose HashMap data structure because I need query() method to be executed in constant time O(1).
So my question is: Is it possible to implement the method query() via HashMap?
If not, what are the alternatives? (Note: the time complexity should be O(1) for query(), not bothering about the space complexity).
Code in the main() :
int[] a = {13,12,13,1,2,0,0,1,3,4};
Range range = new Range(a, 13);
System.out.print(range); // prints [0,0,1,1,2,3,4,12,13,13] because array has been sorted
System.out.print(range.query(1, 4)); // calculating number of elements in the range [1, 4]
Expected Output:
5 // elements 1,1,2,3,4 are within the range [1, 4]
Explanation: provided arguments of the query() are: a=1 and b=4, hence, values to be tested are 1,2,3,4. The output should be 5 because there are 5 elements: 1,1,2,3,4.
To obtain the number of elements in the given range (from a to b inclusive) in O(1) time after the array has been sorted, you don't need to use HashMap. Instead, you can reuse the countingArray by making it an instance variable.
This approach also requires a slight modification of the sorting in order to retain the values in the countingArray intact. It's done by introducing one additional variable.
Note that it's a good practice to avoid mutating the input, that why in the code I've used Arrays.copyOf() (you can remove it, if you consider it irrelevant for this exercise).
I've extracted the logic responsible for sorting from the constructor into a separate method. And introduced a method which is meant to calculate the cumulative count for every number in the array (i.e. a number of element having values from 0 up to the current number inclusive).
So, after invoking method init() on the instance of Range we would be able to find the number of elements in the range from a to b by looking at the values stored in the countingArray at corresponding indices. And that would have a cost O(1).
public class Range {
private int[] arr;
private int[] counterArray;
private int k;
private Range(int[] arr, int k) { // constructor is not exposed
this.arr = Arrays.copyOf(arr, arr.length);
this.counterArray = new int[k + 1];
this.k = k;
}
public static Range getInstance(int[] arr, int k) {
Range range = new Range(arr, k);
range.init();
return range;
}
private void init() {
sort();
sumUpCount();
}
private void sort() {
for (int i : arr) {
counterArray[i]++;
}
int index = 0;
int copy;
for (int i = 0; i < counterArray.length; i++) {
copy = counterArray[i];
while (0 < counterArray[i]) {
arr[index++] = i;
counterArray[i]--;
}
counterArray[i] = copy;
}
}
private void sumUpCount() {
for (int i = 1; i < counterArray.length; i++) {
counterArray[i] += counterArray[i - 1];
}
}
public int query(int a, int b) {
return a == 0 ? counterArray[b] : counterArray[b] - counterArray[a - 1];
}
}
main()
public static void main(String[] args) {
int[] a = {13,12,13,1,2,0,0,1,3,4};
Range range = Range.getInstance(a, 13);
System.out.print(range.query(1,4));
}
Output:
5
Yes, in order to cache/precompute the return values of query(), you need to create a composite key, that holds both values. The easiest way to do that is to use a string that holds both numbers divided by a separator. Separator is important otherwise composite key(21, 5) = "215" and key(2, 15) = "215". With separator that would be "21;5" and "2;15" respectivly.
private String key(int a, int b) {
return String.format("%d;%d", a, b);
}
Then for each composite key possible you put the value into HashMap. In the query(a, b) method you just get the value from the Map.
public query(int a, int b) {
return map.get(key(a, b));
}
The downside of this approach is that creation of this object is pretty expensive.
I was interviewing for one of the big techs where I was asked a programming question in the problem solving round. The question is very similar to the Two Sum problem in Leet Code except for one tricky constraint. The question goes like this :
Given an array of integers nums, an integer target and an integer limit, return exactly one set of elements that counts up to the given limit and adds up to the given target.
Input: nums = [2,7,11,15], target = 20, limit = 3
Output: [2, 7, 11]
Explanation : The target is 20 and the limit is 3, so, we will have to find 3 numbers from the array that add up to 20.
I wasn't able to solve this during the interview and have been searching for a solution ever since.
The brute force approach is to run as many loops as the limit, which is not viable, considering the fact that the limit may be <= 10,000
And another is to extract sub-arrays of length = limit, run through each and every one, add their elements and return a sub-array that adds up to Target.
But, I am sure there must be a more efficient approach to solve this.
Any ideas?
Edit :
The output that we return may be random and not necessarily contiguous.
The limit has to be met and the number of elements that we return must be equal to the limit.
There is no limit on the size of the array
Use Stack (recursively) to find the array elements which will sum to the desired target within the required array elements limit. Doing it this way will actually find all combinations but only those which use fall on the elements limit are placed into a List.
Please read the comments in code. Delete them later if you like. Here is a runnable to demonstrate this process:
package sumtargetlimit_demo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
public class SumTargetLimit_Demo {
// The desired Target Sum
private int targetSum = 20;
/* The max allowable array elements to use in order to acquire
the desired Target Sum. */
private int numbersLimit = 3;
// A Stack to hold the Array elements which sum to the desired Target Sum.
private Stack<Integer> stack = new Stack<>();
// Store the summation of current elements held in stack.
private int sumInStack = 0;
/* A List Interface of Integer[] array to hold all the
combinations of array elements which sum to target. */
private List<Integer[]> combinationsList = new ArrayList<>();
public static void main(String[] args) {
// Demo started this way to avoid the need for statics.
new SumTargetLimit_Demo().startDemo(args);
}
private void startDemo(String[] args) {
// The int array to work against.
int[] intData = {2, 7, 11, 15};
/* See which array elements can acquire the desired
Target Sum with the maximum number of array elements
specified in the numbersLimit member variable. */
getSummations(intData, 0, intData.length);
// Display the found results to Console window...
if (combinationsList.isEmpty()) {
System.err.println("No integer elements within the supplied Array will");
System.err.println("provide a Taget Sum of " + targetSum + " with a maximum number");
System.err.println("limit of " + numbersLimit + ".");
}
else {
for (Integer[] intArray : combinationsList) {
System.out.println(Arrays.toString(intArray).replaceAll("[\\[\\]]", ""));
}
}
}
// Note: This method is recursive...
public void getSummations(int[] data, int startIndex, int endIndex) {
/* Check to see if the sum of array elements stored in the
Stack is equal to the desired Target Sum. If it is then
convert the array elements in the Stack to an Integer[]
Array and add it to the conmbinationsList List. */
if (sumInStack == targetSum) {
if (stack.size() <= numbersLimit) {
combinationsList.add(stack.toArray(new Integer[stack.size()]));
}
}
for (int currIndex = startIndex; currIndex < endIndex; currIndex++) {
if (sumInStack + data[currIndex] <= targetSum) {
stack.push(data[currIndex]);
sumInStack += data[currIndex];
// Make the currentIndex +1, and then use recursion to carry on.
getSummations(data, currIndex + 1, endIndex);
sumInStack -= stack.pop();
}
}
}
}
Try a much larger int[] array and play with the Target Sum and Number Limit to see how things work.
Another way, to look at this problem is through the eyes of dynamic programming. For any element in the array, there are two cases:
It will be a part of the elements, which make up the sum, in that case, we recursively, find the elements that make the remaining sum, with limit - 1.
It will not be part of the elements, which make up the sum, in this case, we look for the target, in the remaining part of the array.
Here, is the sample following the above logic:
import java.util.*;
class HelloWorld {
static Map<Integer, List<Integer>> cache = new HashMap<>();
public static void main(String[] args) {
int[] array = {9, 2, 15, 11, 7, 23, 54, 50, 12};
int limit = 4;
int target = 35;
// This is to optimize the search for element in case the limit is 1
Arrays.sort(array);
List<Integer> subarray = getElementsWithSumEqualToTarget(array, 0, limit, target);
System.out.println(subarray);
}
static List<Integer> getElementsWithSumEqualToTarget(int[] array, int startingIndex, int limit, int target) {
// If limit is 0, or we have reached the end of the array then sum doesn't exists.
if(limit == 0 || startingIndex >= array.length) {
return null;
} else if(limit == 1) {
// For limit 1, we can do a simple binary search, or linear search in that case Arrays.sort can be removed
int index = Arrays.binarySearch(array, startingIndex, array.length - 1, target);
if(index < 0) {
return null;
}
ArrayList<Integer> list = new ArrayList();
list.add(target);
return list;
} else if (cache.containsKey(target)) {
// If for a given sum, the subarray of elements, is already present, we can return it from the cache.(Memoization)
return cache.get(target);
}
// Case 1: The current element will be part of the sum.
List<Integer> subarray = getElementsWithSumEqualToTarget(array, startingIndex + 1, limit - 1, target - array[startingIndex]);
if(subarray != null) {
subarray.add(array[startingIndex]);
// Add target and subarray to the cache
cache.put(target, subarray);
return subarray;
}
// Case 2: Current element is not part of the sum
subarray = getElementsWithSumEqualToTarget(array, startingIndex + 1, limit, target);
if(subarray != null) {
cache.put(target, subarray);
}
return subarray;
}
}
Please try it out on large datasets, and see how it works. Hopefully, it helps.
I have a program that sums the common elements of two arrays. For that I used two for loops and if I have three then I could use three for loops. But how to sum the common elements of n number of arrays where n is coming during run time.
I don't know how to change the number of loops during run time or is there any other relevant concept for this ?
Here is the code I've tried for summing twoarrays:
import java.util.Scanner;
public class Sample {
public static void main(String... args)
{
Scanner sc=new Scanner(System.in);
int arr1[]={1,2,3,4,5},arr2[]={4,5,6,7,8},sum=0;
for (int i=0;i<arr1.length;i++)
{
for (int j=0;j<arr2.length;j++)
{
if (arr1[i]==arr2[j])
{
sum+=(arr1[i]);
}
}
}
}
}
There can be different implementation for that. You can use the following approach. Here is the pseudo code
use a 2D array to store the array. if the number of array is n and size is m then the array will be input[n][m]
Use a ArrayList commonItems to store the common items of. Initiate it with the elements of input[0]
Now iterate through the array for i = 1 to n-1. compare with every input[i], store only the common items of commonItems and input[i] at each step. You can do it by converting the input[i] into a list and by using retainAll method.
At the end of the iteration the commonItem list will contains the common numbers only. Now sum the value of this list.
There is actually a more general method, that also answers the question "how to change the number of loops during run time?".
The general question
We are looking for a way to implement something equivalent to this:
for (i1 = 0; i1 < k1; i1++) {
for (i2 = 0; i2 < k2; i2++) {
for (i3 = 0; i3 < k3; i3++) {
...
for (in = 0; in < kn; in++) {
f(x1[i1], x2[i2], ... xn[in]);
}
...
}
}
}
where, n is given at runtime and f is a function taking a list of n parameters, processing the current n-tuple.
A general solution
There is a general solution, based on the concept of recursion.
This is one implementation that produces the desired behavior:
void process(int idx, int n, int[][] x, int[] k, Object[] ntuple) {
if (idx == n) {
// we have a complete n-tuple,
// with an element from each of the n arrays
f(ntuple);
return;
}
// this is the idx'th "for" statement
for (int i = 0; i < k[idx]; i++) {
ntuple[idx] = x[idx][i];
// with this recursive call we make sure that
// we also generate the rest of the for's
process(idx + 1, n, x, k, ntuple);
}
}
The function assumes that the n arrays are stored in a matrix x, and the first call should look like this:
process(0, n, x, k, new Object[n]);
Practical considerations
The solution above has a high complexity (it is O(k1⋅k2⋅..⋅kn)), but sometimes it is possible to avoid going until the deepest loop.
Indeed, in the specific problem mentioned in this post (which requires summing common elements across all arrays), we can skip generating some tuples e.g. if already x2[i2] ≠ x1[i1].
In the recursive solution, those situations can easily be pruned. The specific code for this problem would probably look like this:
void process(int idx, int n, int[][] x, int[] k, int value) {
if (idx == n) {
// all elements from the current tuple are equal to "value".
// add this to the global "sum" variable
sum += value;
return;
}
for (int i = 0; i < k[idx]; i++) {
if (idx == 0) {
// this is the outer "for", set the new value
value = x[0][i];
} else {
// check if the current element from the idx'th for
// has the same value as all previous elements
if (x[idx][i] == value) {
process(idx + 1, n, x, k, value);
}
}
}
}
Assuming that the index of the element is not important: a[1] = 2 and a[5] = 2, you only need two nested loops.
First you need to put n-1 arrays in a list of sets. Then loop over nth array and check if each element exists in all of the sets in the list. If it does exist then add to total.
I am trying to solve the below 'codility' exercise:
A zero-indexed array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.
Your goal is to find that missing element.
Write a function:
class Solution { public int solution(int[] A); }
that, given a zero-indexed array A, returns the value of the missing element.
For example, given array A such that:
A[0] = 2
A[1] = 3
A[2] = 1
A[3] = 5
the function should return 4, as it is the missing element.
Assume that:
N is an integer within the range [0..100,000];
the elements of A are all distinct;
each element of array A is an integer within the range [1..(N + 1)].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
I came up with two solutions:
1) Gives 100%/100%
class Solution {
public int solution(int[] A) {
int previous = 0;
if (A.length != 0) {
Arrays.sort(A);
for (int i : A) {
if (++previous != i) {
return previous;
}
}
}
return ++previous;
}
}
2) Gives an error WRONG ANSWER, got 65536 expected 100001
class SolutionHS {
public int solution(int[] A) {
int previous = 0;
HashSet<Integer> hs = new HashSet<>();
if (A.length != 0) {
for (int a : A) {
hs.add(a);
}
for (Integer i : hs) {
if (++previous != i) {
return previous;
}
}
}
return ++previous;
}
}
My question is:
Shouldn't both approaches (using hashset and Arrays.sort) work the same way?
If not can you tell me what the difference is?
HashSet is not sorted, so when you iterate over the elements of the Set, you don't get them in an ascending order, as your code expects. If you used a TreeSet instead of HashSet, your code would work.
The HashSet solution will give the correct answer if you change the second loop to :
for (int i = 0; i <= A.length; i++) {
if (!hs.contains(i)) {
return i;
}
}
This loop explicitly checks whether each integer in the relevant range appears in the HashSet and returns the first (and only one) which doesn't.
Anyway, both your implementations don't meet the O(n) running time and O(1) space requirements.
In order you meet the required running time and space, you should calculate the sum of the elements of the array and subtract that sum from (A.length+1)*A.length/2.
A zig-zag method which takes an array as argument and returns a zig-zag array.
Example : Input 2,6,1,7,9,3
Output 9,1,7,2,6,3
The array returned must have alternative highest numbers and lowest numbers.
I can think of this method.
//Pseudo code
public static int [] zig-zag(int arr[])
{
arr.sort();
int returnArr[] = new int[arr.length];
int begindex = 0, endindex = arr.length -1;
int idx = 0;
while(begindex<arr.length/2-1 && endindex>=arr.length/2)
{
returnArr[idx++] = arr[endindex];
returnArr[idx++] = arr[begindex];
begindex++;endindex--;
}
if(arr.length%2 == 1)
reurnArr[idx] = arr[begindex];
return returnArr;
}
This method has a time complexity of O(nlogn) (because of the sort) and space complexity of O(n).
Is there any other way/algorithm so that it can do better than O(nlogn) ? or with O(nlogn) and space complexity being O(1) ?
There's one more method with TC O(n^2) and SC O(1). But not interested in TC of O(n^2).
Here is an algorithm that can do it with time complexity O(nlogn) and space complexity O(1) using a linked list.
The method works for lists with duplicate values.
It is as follows:
First, get your list, l, sorted in descending order, with the second half reversed. (Note that your sorting algorithm must work in place on a linked list, such as in place merge sort.)
For example, with l = 2, 6, 1, 7, 9, 3, this form would be l = 9, 7, 6, 1, 2, 3. If your list was of odd length, the first half would be one element longer than the second.
An easy way to do this would be to sort l in descending order, and then reverse the elements in the second half.
Next, we create some temporary variables:
Node upper = list.head; //Upper half of list pointer
Node lower = list.get(l.length/2); //Lower half of list pointer
Node temp = null; //Utility pointer to hold whatever we need
//Let's set up our initial state
list.get(l.length/2-1) = null; //Disconnect two halves of the list
temp = upper.next; //Hold upper half minus head
upper.next = lower; //First element of upper half stitched to bottom half
//Note that lower would need to be at `l.length/2+1` for an odd length list
//This also applies to list.get in the set up
//The code could be generalized to both even and odd lenghts by using `Math.ceil`
// or a similar function to round up instead of Java's default of rounding down
zigZag(upper, lower, temp); //Call to algorithm
Finally, the algorithm:
public static void zigZag(Node upper, Node lower, Node temp){
int i = 0; //Controls alternation
while(temp != null){ //Until temp gets set to null by lower.next or upper.next
if(i%2==0){ //On even iterations
upper = temp;
temp = lower.next;
lower.next = upper;
}
else{ //On odd iterations
lower = temp;
temp = upper.next;
upper.next = lower;
}
i++;
}
}
Alternatively, here's the recursive version:
public static void zigZag(Node upper, Node lower, Node temp){
if(temp == null) // temp got set to null by lower.next or upper.next
return; // we're done
upper = temp;
temp = lower.next;
lower.next = upper;
zigZag(lower, upper, temp); //swap upper/lower for next cycle
}
You now have a zig-zagged linked list, stored in l.
Finding time and space complexity:
Sorting: time O(nlogn), space O(1)
Sorting takes your original time complexity and, as it sorts in place, constant space
Reversing: time O(n), space O(1)
Reversing the second half of your list is O(n/2) => O(n)
Temporaries: time O(1), space O(1)
Simple variable assignments of constant number and size take both constant time and space
Algorithm: time O(n), space O(1)
The algorithm simply changes the next pointer of each node once, so it runs in O(n) time. It doesn't create any new variables, and thus has constant space complexity, O(1).
The recursive version is tail recursive, which means it can only use a single stack frame, giving it theoretically constant space complexity, O(1). (Though not in Java, as it does not support tail-recursion optimization.)
Adding it all up:
As you can see, space complexity is constant throughout, giving our overall program O(1) space usage.
Time complexity is O(nlogn)+O(n)+O(1)+O(n), which is clearly dominated by O(nlogn).
Extra reversing of your linked list because you used an ascending order sort will slow the program, but won't change the overall time complexity.
Similarly, you could come up with a sort that gives the desired form of half descending, half ascending to save some time, but it too would not change overall time complexity.
Potential for Speedup:
As mentioned by #flkes in his answer, you can reduce the time complexity of your whole program by reducing the time complexity of the sort, as it produces the dominating term.
If you found an implementation that sorted in place in O(n) time (such as this linked-list radix sort algorithm or a similar bucket sort algorithm), you could achieve total time complexity of O(n) with constant, O(1), space complexity, which is really incredibly good.
I would recommend implementing a radix sort first, which has a complexity of O(n). An example of that can be found here
Once you radix sort the list you can easily map it to the zigzag pattern using a container with a simple for loop. This should push the complexity to some O(n + kn) which still resolves to O(n)
After sorting, invert the second half of the array:
now the rest of the problem is to do a perfect shuffle of the array elements - a problem to come up time and again.
If you want to apply a permutation in-place and know how to transform indices, you can keep a "scoreboard" of indices handled - but even a single bit per item is O(n) storage. (Find the next index still needing handling and perform the cycle containing it, keeping scores, until all indices are handled.)
A pretty nice rendition of an in-place perfect shuffle in linear time and constant space in addition to the array is Aryabhata's over at CS. The method has been placed at arxiv.org by Peiyush Jain.
(The complexity of the sort as a first step may dominate the permutation/shuffle step(s).)
There is another interpretation of this task, or the sort step: sort into a folded array.
The sort lending itself most readily to this task got to be the double-ended selection sort:
In each pass over the data not yet placed, determine the min and max in 3/2n comparisons and swap into their positions, until one value or none at all is left.
Or take a standard sort method, and have the indexes mapped. For the hell of it:
/** Anything with accessors with int parameter */
interface Indexable<T> {
T get(int index);
T set(int index, T value);
// int size(); // YAGNI?
}
/** The accessors have this folded in half,
* while iterator() is not overridden */
#SuppressWarnings("serial")
class FoldedList<T> extends ArrayList<T>
implements Indexable<T> {
public FoldedList(#SuppressWarnings("unchecked") T...elements) {
super(Arrays.asList(elements));
}
int map(int index) {
final int last = size()-1;
index = 2*index;
return last <= index ? 2*last-index : index+1;
}
#Override
public T get(int index) { return super.get(map(index)); }
#Override
public T set(int index, T element) {
return super.set(map(index), element);
}
}
/** Sort an Indexable<T> */
public class Sort {
// Hoare/Sedgewick using middle index for pivot
private static <T extends Comparable<T>>
int split(Indexable<T> ixable, int lo, int hi) {
int
mid = lo + (hi-lo)/2,
left = lo+1,
right= hi-1;
T pivot = ixable.get(mid),
l = null, r = null;
ixable.set(mid, ixable.get(lo));
scan:
while (true) {
while ((l = ixable.get(left)).compareTo(pivot) < 0)
if (right < ++left) {
left--;
break scan;
}
while (pivot.compareTo(r = ixable.get(right)) < 0)
if (--right <= left) {
left -= 1;
l = ixable.get(left);
break scan;
}
ixable.set(left, r); // place misplaced items
ixable.set(right, l);
if (--right < ++left) {
left = right;
l = r;
break;
}
}
ixable.set(lo, l); // put last left value into first position
ixable.set(left, pivot); // place pivot at split index
return left;
}
private static <T extends Comparable<T>>
void sort(Indexable<T> ixable, int lo, int hi) {
while (lo+2 < hi) { // more than 2 Ts
int split = split(ixable, lo, hi);
if (split - lo < hi - split) {
sort(ixable, lo, split); // left part smaller
lo = split + 1;
} else {
sort(ixable, split+1, hi); // right part smaller
hi = split;
}
}
T l, h;
if (lo < --hi // 2 Ts
&& (l = ixable.get(lo)).compareTo(h = ixable.get(hi)) > 0) {
ixable.set(lo, h); // exchange
ixable.set(hi, l);
}
}
public static <T extends Comparable<T>>
void main(String[] args) {
Indexable<Number> nums = new FoldedList<>( //2,6,1,7,9,3);
7, 3, 9, 3, 0, 6, 1, 2, 8, 6, 5, 4, 7);
sort((Indexable<T>) nums);
System.out.println(nums);
}
}