Java Quick Sort Optimization - java

I have three classes. Each creates an array of 1000 int values.
class a: uses QuickSort
class b: uses QuickSort until the size of each partition is <10 then executes InsertSort for sorting the smaller partitions.
class c: (this is the one I'm having trouble with): same as class b except executes InsertSort on the whole almost sorted array.
It would seem that class c is only a slight variation of the code in class b (which basically adds to class a). I just don't really know HOW to make this happen... Help! Thanks in advanced...
Class a:
import java.util.Arrays;
import java.util.Random;
public class QuickSort {
private static final Random random = new Random();
private static final int RANDOM_INT_RANGE = 9999;
private static int[] randomArray(int size) {
// Randomize data (array)
final int[] arr = new int[size];
for (int i = 0; i < arr.length; i++) {
arr[i] = random.nextInt(RANDOM_INT_RANGE);
}
return arr;
}
// Sort
private static void sort(int[] arr) {
if (arr.length > 0)
sortInPlace(arr, 0, arr.length - 1);
}
private static void sortInPlace(int[] arr, int left, int right) {
if (left >= right)
return; // sorted
final int range = right - left + 1;
int pivot = random.nextInt(range) + left;
int newPivot = partition(arr, left, right, pivot);
sortInPlace(arr, left, newPivot - 1);
sortInPlace(arr, newPivot + 1, right);
}
private static int partition(int[] arr, int left, int right, int pivot) {
int pivotVal = arr[pivot];
swapArrayVals(arr, pivot, right);
int storeIndex = left;
for (int i = left; i <= (right - 1); i++) {
if (arr[i] < pivotVal) {
swapArrayVals(arr, i, storeIndex);
storeIndex++;
}
}
swapArrayVals(arr, storeIndex, right);
return storeIndex;
}
private static void swapArrayVals(int[] arr, int from, int to) {
int fromVal = arr[from];
int toVal = arr[to];
arr[from] = toVal;
arr[to] = fromVal;
}
public static void main(String[] args) {
long StartTime = System.nanoTime();
// Array size
int[] arr = randomArray(1000);
int[] copy = Arrays.copyOf(arr, arr.length);
// Print original data (array)
System.out.println("The starting/unsorted array: \n"
+ Arrays.toString(arr));
sort(arr);
// check the result
Arrays.sort(copy);
if (Arrays.equals(arr, copy)) {
System.out.println("The ending/sorted array: \n"
+ Arrays.toString(arr));
// print time
long TotalTime = System.nanoTime() - StartTime;
System.out.println("Total elapsed time (milliseconds) " + "is: "
+ TotalTime);
}
}
}
Class b:
import java.util.Arrays;
import java.util.Random;
public class OptQSort1 {
private static final Random random = new Random();
private static final int RANDOM_INT_RANGE = 9999;
private static int[] randomArray(int size) {
// Randomize data (array)
final int[] arr = new int[size];
for (int i = 0; i < arr.length; i++) {
arr[i] = random.nextInt(RANDOM_INT_RANGE);
}
return arr;
}
// Sort
private static void sort(int[] arr) {
if (arr.length > 0)
sortInPlace(arr, 0, arr.length - 1);
}
private static void sortInPlace(int[] arr, int left, int right) {
boolean insertionSortCalled = false;
// OptQSort1:
int size = right - left + 1;
if (size < 10 && !insertionSortCalled) {
insertionSortCalled = true;
insertionSort(arr, 0, arr.length - 1);
}
if (left >= right)
return; // sorted
final int range = right - left + 1;
int pivot = random.nextInt(range) + left;
int newPivot = partition(arr, left, right, pivot);
sortInPlace(arr, left, newPivot - 1);
sortInPlace(arr, newPivot + 1, right);
}
private static int partition(int[] arr, int left, int right, int pivot) {
int pivotVal = arr[pivot];
swapArrayVals(arr, pivot, right);
int storeIndex = left;
for (int i = left; i <= (right - 1); i++) {
if (arr[i] < pivotVal) {
swapArrayVals(arr, i, storeIndex);
storeIndex++;
}
}
swapArrayVals(arr, storeIndex, right);
return storeIndex;
}
private static void swapArrayVals(int[] arr, int from, int to) {
int fromVal = arr[from];
int toVal = arr[to];
arr[from] = toVal;
arr[to] = fromVal;
}
public static void insertionSort(int[] arr, int left, int right) {
int in, out;
for (out = left + 1; out <= right; out++) {
int temp = arr[out];
in = out;
while (in > left && arr[in - 1] >= temp) {
arr[in] = arr[in - 1];
--in;
}
arr[in] = temp;
}
}
public static void main(String[] args) {
long StartTime = System.nanoTime();
// Array size
int[] arr = randomArray(1000);
int[] copy = Arrays.copyOf(arr, arr.length);
// Print original data (array)
System.out.println("The starting/unsorted array: \n"
+ Arrays.toString(arr));
sort(arr);
// check the result
Arrays.sort(copy);
if (Arrays.equals(arr, copy)) {
System.out.println("The ending/sorted array: \n"
+ Arrays.toString(arr));
// print time
long TotalTime = System.nanoTime() - StartTime;
System.out.println("Total elapsed time (milliseconds) " + "is: "
+ TotalTime);
}
}
}
Class c:
import java.util.Arrays;
import java.util.Random;
public class OptQSort2 {
private static final Random random = new Random();
private static final int RANDOM_INT_RANGE = 9999;
private static int[] randomArray(int size) {
// Randomize data (array)
final int[] arr = new int[size];
for (int i = 0; i < arr.length; i++) {
arr[i] = random.nextInt(RANDOM_INT_RANGE);
}
return arr;
}
// Sort
private static void sort(int[] arr) {
if (arr.length > 0)
sortInPlace(arr, 0, arr.length - 1);
insertionSort(arr, 0, arr.length - 1);
}
private static void sortInPlace(int[] arr, int left, int right) {
// OptQSort2:
int size = right - left + 1;
if (size < 10)
return;
if (left >= right)
return; // sorted
final int range = right - left + 1;
int pivot = random.nextInt(range) + left;
int newPivot = partition(arr, left, right, pivot);
sortInPlace(arr, left, newPivot - 1);
sortInPlace(arr, newPivot + 1, right);
}
private static int partition(int[] arr, int left, int right, int pivot) {
int pivotVal = arr[pivot];
swapArrayVals(arr, pivot, right);
int storeIndex = left;
for (int i = left; i <= (right - 1); i++) {
if (arr[i] < pivotVal) {
swapArrayVals(arr, i, storeIndex);
storeIndex++;
}
}
swapArrayVals(arr, storeIndex, right);
return storeIndex;
}
private static void swapArrayVals(int[] arr, int from, int to) {
int fromVal = arr[from];
int toVal = arr[to];
arr[from] = toVal;
arr[to] = fromVal;
}
public static void insertionSort(int[] arr, int left, int right) {
int in, out;
for (out = left + 1; out <= right; out++) {
int temp = arr[out];
in = out;
while (in > left && arr[in - 1] >= temp) {
arr[in] = arr[in - 1];
--in;
}
arr[in] = temp;
}
}
public static void main(String[] args) {
// Start the clock
long StartTime = System.nanoTime();
// Array size
int[] arr = randomArray(1000);
int[] copy = Arrays.copyOf(arr, arr.length);
// Print original data (array)
System.out.println("The starting/unsorted array: \n"
+ Arrays.toString(arr));
sort(arr);
// check the result
Arrays.sort(copy);
if (Arrays.equals(arr, copy)) {
System.out.println("The ending/sorted array: \n"
+ Arrays.toString(arr));
// print time
long TotalTime = System.nanoTime() - StartTime;
System.out.println("Total elapsed time (milliseconds) " + "is: "
+ TotalTime);
}
}
}

You're saying that class c just implements insertion-sort, with no quick-sort at all, right?
Then in principle, class c could just be class b, with this line:
sort(arr);
changed to this:
insertionSort(arr, 0, arr.length);
(And then you'd want to start stripping out a lot of code — removing methods that are never called, modifying the insertionSort method to assume that left is 0 and right is arr.length rather than requiring them to be specified, renaming the insertionSort method to sort, etc.)
By the way, class c is actually much easier than the classes you've already managed to create. You probably just need to get some sleep. You'll have no problem with it in the morning. :-)

To create class c copy class b and then change it in the following way:
Add instance variable insertionSortCalled so you don't call insertion sort multiple times in different recursive calls
boolean insertionSortCalled= false;
And change this part to the following: insertionSort(arr, 0, arr.length-1);
private static void sortInPlace(int[] arr, int left, int right) {
// OptQSort1:
int size = right - left + 1;
**if (size < 10 && !insertionSortCalled){**
**insertionSortCalled=true;**
**insertionSort(arr, 0, arr.length-1);**
}
if (left >= right)
return; // sorted
final int range = right - left + 1;
int pivot = random.nextInt(range) + left;
int newPivot = partition(arr, left, right, pivot);
sortInPlace(arr, left, newPivot - 1);
sortInPlace(arr, newPivot + 1, right);
}

Related

What is wrong the the merge function in my mergesort code?

Sorry, beginner here.This is what I have right now:
public class MergeSort
{
public static void main(String[] args)
{
int[] arr = {3, 5, 2, 4, 1};
sort(arr, 0, arr.length - 1);
for(int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
}
private static void sort(int[] arr, int lo, int hi)
{
if(lo >= hi)
{
return;
}
int mid = (lo + hi)/2;
sort(arr, lo, mid);
sort(arr, mid + 1, hi);
int size = hi - lo + 1;
int[] temp = new int[size]; //new array to merge into
merge(arr, temp, lo, mid + 1, hi);
for(int i = 0; i < size; i++)
{
arr[i + lo] = temp[i];
}
}
private static void merge(int[] arr, int[] temp, int lower, int mid, int upper)
{
int tempIndex = 0;
int leftLo = lower;
int leftHi = mid - 1;
int rightLo = mid;
int rightHi = upper;
while(leftLo <= leftHi && rightLo <= rightHi)
{
if(arr[leftLo] < arr[rightLo])
{
temp[tempIndex] = arr[leftLo];
tempIndex++;
leftLo++;
}
else
{
temp[tempIndex] = arr[rightLo];
tempIndex++;
rightLo++;
}
}
}
}
I know it's the merge function that is not working, because right now it prints out only the smallest element and the rest as 0's. I think it has something to do with needing another while loop to copy the array, but I don't know how to write that, or even the purpose of it, as right now it seems that the array is being merged into the temp array in a correct order. Why is it only printing the first element correctly? Thanks.
In merge, you copy values as long as leftLo and rightLo both haven't reached their limit yet. Typically one of them reaches early. Then you need to copy the remaining values of the other one. You can copy the remaining elements by adding these two loops:
while (leftLo <= leftHi) {
temp[tempIndex] = arr[leftLo];
tempIndex++;
leftLo++;
}
while (rightLo <= rightHi) {
temp[tempIndex] = arr[rightLo];
tempIndex++;
rightLo++;
}
That is, the complete method becomes:
private static void merge(int[] arr, int[] temp, int lower, int mid, int upper) {
int tempIndex = 0;
int leftLo = lower;
int leftHi = mid - 1;
int rightLo = mid;
int rightHi = upper;
while (leftLo <= leftHi && rightLo <= rightHi) {
if (arr[leftLo] < arr[rightLo]) {
temp[tempIndex] = arr[leftLo];
tempIndex++;
leftLo++;
} else {
temp[tempIndex] = arr[rightLo];
tempIndex++;
rightLo++;
}
}
while (leftLo <= leftHi) {
temp[tempIndex] = arr[leftLo];
tempIndex++;
leftLo++;
}
while (rightLo <= rightHi) {
temp[tempIndex] = arr[rightLo];
tempIndex++;
rightLo++;
}
}

Java QuickSort Best Case Array Generation

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);
}

Quicksort: Almost sorted, but not quite. What's wrong?

Here's the code. The output is a very nearly correctly sorted array, but there are several elements out of order. Anyone able to spot the error?
I'm pretty sure the swap and quicksort methods are correct, but I'm posting all the methods here just in case.
package quicksort;
import java.util.Random;
import java.util.Arrays;
public class QuickSort {
/**
* #param args the command line arguments
*/
private static int[] u;
public static void main(String[] args) {
u = makeArray(100);
System.out.println(Arrays.toString(u));
quicksort(0, u.length - 1);
System.out.println(Arrays.toString(u));
}
public static int[] makeArray(int n) {
int[] a = new int[n];
int j;
Random r = new Random();
for (int i = 0; i < n; i++) {
j = (r.nextInt(100) + 1);
a[i] = j;
}
return a;
}
public static int partition(int left, int right, int pivot) {
int p = pivot; // pivot
int lPt = left - 1;
int rPt = right + 1;
while (true) {
while ((lPt < right) && (u[++lPt] < p));
while ((rPt > left) && (u[--rPt] > p));
if (lPt >= rPt) {
break;
} else {
swap(lPt, rPt);
System.out.println("Swapping " + lPt + " " + rPt);
}
}
return lPt;
}
public static void swap (int a, int b) {
int temp = u[a];
u[a] = u[b];
u[b] = temp;
}
public static void quicksort(int l, int r) {
if (r - l <= 0) {
return;
} else {
int part = partition(l, r, u[l]);
quicksort (l, part - 1);
quicksort (part + 1, r);
}
}
}
The problem is in the partition method. The pivot element is not being placed in its correct position at the end of your swaps. I've changed the method signature so that you pass in the position of the pivot element, rather than the value of the pivot, so in quicksort() you would now write:
int part = partition(l, r, l);
In the body of the pivot method, I swapped the pivot element to the end of the section (by swapping with right). So that we then ignore this element with our swaps, I took away the "+ 1" on the initialisation of rPT. I then added a statement after your while loop to move the pivot element into place. With those three changes, the method now looks like this:
public static int partition(int left, int right, int pivotPosition) {
int p = u[pivotPosition]; // pivot
// Move pivot to the end
swap(pivotPosition, right);
int lPt = left - 1;
int rPt = right;
while (true) {
while ((lPt < right) && (u[++lPt] < p));
while ((rPt > left) && (u[--rPt] > p));
if (lPt >= rPt) {
break;
} else {
swap(lPt, rPt);
System.out.println("Swapping " + lPt + " " + rPt);
}
}
// Put pivot in its place
swap(lPt, right);
return lPt;
}
With these changes, the code works for me.
You have to find a values in the left list which is larger than the pivot element and find a value in the right list which is smaller then the pivot element then we exchange the values.
package quicksort;
import java.util.Random;
import java.util.Arrays;
public class QuickSort {
/**
* #param args the command line arguments
*/
private static int[] u;
public static void main(String[] args) {
u = makeArray(10);
System.out.println(Arrays.toString(u));
quicksort(0, u.length - 1);
System.out.println(Arrays.toString(u));
}
public static int[] makeArray(int n) {
int[] a = new int[n];
int j;
Random r = new Random();
for (int i = 0; i < n; i++) {
j = (r.nextInt(100) + 1);
a[i] = j;
}
return a;
}
private static void quicksort(int low, int high) {
int i = low, j = high;
int pivot = u[low];
while (i <= j) {
while (u[i] < pivot) {
i++;
}
while (u[j] > pivot) {
j--;
}
if (i <= j) {
exchange(i, j);
i++;
j--;
}
}
if (low < j) {
quicksort(low, j); // note here
}
if (i < high) {
quicksort(i, high); // note here
}
}
private static void exchange(int i, int j) {
int temp = u[i];
u[i] = u[j];
u[j] = temp;
}
}

Mergesort - Stackoverflow when splitting array not in a half

I've a problem.
I have to edit the standard mergesort algorithm, changing the ratio between the two halves of the array. Standard mergesort splits array in 2. BUT I've to split it with a coefficient.
Example:
I've a 10elements array, and i've to split it with a coeff of 0.2. This means that the first time the array is divided in 2 parts: one with 2 elements, the second with 8 elements. Being recursive, this ratio is applied every time I split the array.
The problem:
If the coeff >=0.5 no probs. If the ratio in <=0.5 every attempt leads to a stackoverflow.
Any help will be kindly appreciated!
Here the class:
public class Sort {
public static double coeff = 0.2;
public static void mergeSort(int[] a) {
int vectorTemp[];
vectorTemp = new int[a.length];
mergeSort(a, vectorTemp, 0, a.length - 1);
}
private static void mergeSort(int[] a, int[] vectorTemp, int left, int right) {
if (left < right) {
int center = calculateMid(left, right);
mergeSort(a, vectorTemp, left, center);
mergeSort(a, vectorTemp, center + 1, right);
merge(a, vectorTemp, left, center + 1, right);
}
}
private static void merge(int[] a, int[] vectorAux, int posLeft, int posRight, int posEnd) {
int endLeft = posRight - 1;
int posAux = posLeft;
int numElemen = posEnd - posLeft + 1;
while (posLeft <= endLeft && posRight <= posEnd) {
if ((a[ posLeft]) < (a[posRight])) {
vectorAux[posAux++] = a[posLeft++];
} else {
vectorAux[posAux++] = a[posRight++];
}
}
while (posLeft <= endLeft) {
vectorAux[posAux++] = a[posLeft++];
}
while (posRight <= posEnd) {
vectorAux[posAux++] = a[posRight++];
}
for (int i = 0; i < numElemen; i++, posEnd--) {
a[posEnd] = vectorAux[posEnd];
}
}
//this is the method i've added to calculate the size
private static int calculateMid(int left, int right){
int mid = 0;
int tot = right-left+1;
int firstHalf = (int) (tot * coeff);
mid = left + firstHalf;
System.out.println(left+", "+mid +", "+firstHalf+", "+right + ", "+tot);
return mid-1;
}
public static void main(String[] args) {
int vector2[] = {10, 3, 15, 2, 1, 4, 9, 0};
System.out.println("Array not ordered: " + Arrays.toString(vector2) + "\n");
mergeSort(vector2);
System.out.println("Array ordered: " + Arrays.toString(vector2));
}}
Here is a hint:
Think about what calculateMid() returns for a two-element array, and what happens in mergeSort() after that.
Once you figure out what happens there, it will also become clear why the code works for coeff >= 0.5.

Java recursive insertion sort?

So I am trying to make the following code into a recursive method, insertion sort, but for as much as I try I cannot. Can anyone help me?
public static void insertionSort(int[] array){
for (int i = 1; i < array.length; i++){
int j = i;
int B = array[i];
while ((j > 0) && (array[j-1] > B)){
array[j] = array[j-1];
j--;
}
array[j] = B;
}
}
EDIT:
I was thinking of something like this, but it doesn't look very recursive to me...
public static void insertionSort(int[] array, int index){
if(index < array.length){
int j = index;
int B = array[index];
while ((j > 0) && (array[j-1] > B)){
array[j] = array[j-1];
j--;
}
array[j] = B;
insertionSort(array, index + 1);
}
}
Try this:
public class RecursiveInsertionSort {
static int[] arr = {5, 2, 4, 6, 1, 3};
int maxIndex = arr.length;
public static void main(String[] args) {
print(arr);
new RecursiveInsertionSort().sort(arr.length);
}
/*
The sorting function uses 'index' instead of 'copying the array' in each
recursive call to conserve memory and improve efficiency.
*/
private int sort(int maxIndex) {
if (maxIndex <= 1) {
// at this point maxIndex points to the second element in the array.
return maxIndex;
}
maxIndex = sort(maxIndex - 1); // recursive call
// save a copy of the value in variable 'key'.
// This value will be placed in the correct position
// after the while loop below ends.
int key = arr[maxIndex];
int i = maxIndex - 1;
// compare value in 'key' with all the elements in array
// that come before the element key.
while ((i >= 0) && (arr[i] > key)) {
arr[i+1] = arr[i];
i--;
}
arr[i+1] = key;
print(arr);
return maxIndex + 1;
}
// code to print the array on the console.
private static void print(int[] arr) {
System.out.println();
for (int i : arr) {
System.out.print(i + ", ");
}
}
}
public static void insertionSort(int[] array, int index) {
if(array.length == index + 1) return;
insertionSort(array, index + 1);
// insert array[index] into the array
}
You can try this code. It works correctly.
public static int[] InsertionSort(int[] dizi, int n)
{
int i;
if (n < 1) {
InsertionSort(dizi, n - 1);
}
else {
int key = dizi[n];
i = n - 1;
while (i >= 0 && dizi[i] > key) {
dizi[i + 1] = dizi[i];
i = i - 1;
}
dizi[i + 1] = key;
}
return dizi;
}
for the recursion algorithm, we start with the whole array A[1..n], we sort A[1..n-1] and then insert A[n] into the correct position.
public int[] insertionSort(int[] array)
{
//base case
if(array.length==1) return new int[]{ array[0] };
//get array[0..n-1] and sort it
int[] arrayToSort = new int[array.length - 1]{ };
System.arraycopy(array, 0, arrayToSort, 0, array.length -1);
int[] B = insertionSort(arrayToSort);
//now, insert array[n] into its correct position
int[] C = merge(B, array[array.length - 1]);
return C;
}
private int[] merge(int[] array, int n)
{
int[] arrayToReturn = new int[array.length + 1] {};
int j = array.length-1;
while(j>=0 && n <= array[j])
{
arrayToReturn[j+1]=array[j;
j--;
}
arrayToReturn[j] =
}
Try below code by providing ele as an integer array, sortedIndex=index of first element and index=index of second element:
public static void insertionSort(int[] ele, int sortedIndex, int index) {
if (sortedIndex < ele.length) {
if (index < ele.length) {
if (ele[sortedIndex] > ele[index]) {
ele[sortedIndex] += ele[index];
ele[index] = ele[sortedIndex] - ele[index];
ele[sortedIndex] = ele[sortedIndex] - ele[index];
}
insertionSort(ele, sortedIndex, index + 1);
return;
}
if (index == ele.length) {
sortedIndex++;
}
insertionSort(ele, sortedIndex, sortedIndex + 1);
}
}
public static void sort(int[] A, int p, int r) {
if (p < r) {
int q = r - 1;
sort(A, p, q);
combine(A, p, q, r);
}
}
private static void combine(int[] A, int p, int q, int r) {
int i = q - p;
int val = A[r];
while (i >= 0 && val < A[p + i]) {
A[p + i + 1] = A[p + i];
A[p + i] = val;
i--;
}
}
public static void main(String... strings) {
int[] A = { 2, 5, 3, 1, 7 };
sort(A, 0, A.length - 1);
Arrays.stream(A).sequential().forEach(i -> System.out.print(i + ", "));
}
public class test
{
public static void main(String[] args){
test h = new test();
int a[] = { 5, 8, 9, 13, 65, 74, 25, 44, 67, 2, 1 };
h.ins_rec(a, a.length-1);
for(int i=0; i<a.length; i++)
log(a[i]);
}
void ins_rec(int a[], int j){
if( j == 0 ) return;
ins_rec(a, j - 1);
int key = a[ j ];
sort(a, key, j - 1);
}
void sort(int a[], int key, int i){
if( (i < 0) || (a[i] < key) ) {
a[ i + 1 ] = key;
return;
}
a[ i + 1 ] = a[ i ];
sort(a, key, i - 1);
}
private static void log(int aMessage){
System.out.println("\t\t"+aMessage);
}
}

Categories