Data Structures - java

I am coding a program which is basically going to compute the number of inversions in the array. The requirement is to use a divide-and-conquer algorithm.
I have used merge sort but afterwards I am stuck. I need to create another method called count in order to count the inversions using recursion. Here I need your help...
Thank you in advance
import java.util.*;
public class inversions
{
public static void main(String[] args)
{
Integer[] a = {2, 6, 3, 5, 1};
mergeSort(a);
System.out.println(Arrays.toString(a));
}
public static void mergeSort(Comparable [ ] a)
{
Comparable[] tmp = new Comparable[a.length];
mergeSort(a, tmp, 0, a.length - 1);
}
private static void mergeSort(Comparable [ ] a, Comparable [ ] tmp, int left, int right)
{
if( left < right )
{
int center = (left + right) / 2;
mergeSort(a, tmp, left, center);
mergeSort(a, tmp, center + 1, right);
merge(a, tmp, left, center + 1, right);
}
}
private static void merge(Comparable[ ] a, Comparable[ ] tmp, int left, int right, int rightEnd )
{
int leftEnd = right - 1;
int k = left;
int num = rightEnd - left + 1;
while(left <= leftEnd && right <= rightEnd)
if(a[left].compareTo(a[right]) <= 0)
tmp[k++] = a[left++];
else
tmp[k++] = a[right++];
while(left <= leftEnd) // Copy rest of first half
tmp[k++] = a[left++];
while(right <= rightEnd) // Copy rest of right half
tmp[k++] = a[right++];
// Copy tmp back
for(int i = 0; i < num; i++, rightEnd--)
a[rightEnd] = tmp[rightEnd];
}
public int count(int[] A, int n){}
}

Added some changes in Your Code.
import java.util.*;
public class inversions
{
public static int countInversions = 0;
public static void main(String[] args)
{
Integer[] a = {2, 6, 3, 5, 1};
mergeSort(a);
System.out.println(Arrays.toString(a));
System.out.println(countInversions);
}
public static void mergeSort(Comparable [ ] a)
{
Comparable[] tmp = new Comparable[a.length];
mergeSort(a, tmp, 0, a.length - 1);
}
private static void mergeSort(Comparable [ ] a, Comparable [ ] tmp, int left, int right)
{
if( left < right )
{
int center = (left + right) / 2;
mergeSort(a, tmp, left, center);
mergeSort(a, tmp, center + 1, right);
merge(a, tmp, left, center + 1, right);
}
}
private static void merge(Comparable[ ] a, Comparable[ ] tmp, int left, int right, int rightEnd )
{
int leftEnd = right - 1;
int k = left;
int num = rightEnd - left + 1;
while(left <= leftEnd && right <= rightEnd)
if(a[left].compareTo(a[right]) <= 0)
tmp[k++] = a[left++];
else {
countInversions+=((leftEnd-left)+1); // Counts the inversions
tmp[k++] = a[right++];
}
while(left <= leftEnd) // Copy rest of first half
tmp[k++] = a[left++];
while(right <= rightEnd) // Copy rest of right half
tmp[k++] = a[right++];
// Copy tmp back
for(int i = 0; i < num; i++, rightEnd--)
a[rightEnd] = tmp[rightEnd];
}
}
In the above code, we are counting the inversions when two arrays are merging. For example 1st sub-array contains [1, 6] and 2nd sub-array has [2, 3]. So when these are merged together inversion count will be 2 i.e. [6>2] & [6>3]. When the condition comes that a[left] > a[right] it will count the number of elements remaining on the right sub-array because will be less than the a[left] and will add them to countInversions.

Related

Java QuickSort algorithm

I am trying to learn Quick Sort algorithm and this is my code so far:
import java.util.Arrays;
public class JavaFiddle {
static int[] myArray = new int[]{35, 12, 25, 1, 5, 33, 56};
public static void QuickSort(int[] array) {
QuickSort(array, 0, array.length - 1);
}
public static void QuickSort(int[] array, int left, int right) {
if (left < right) {
int pivot = left + ((right - left) / 2);
int index = partition(array, left, right, pivot);
QuickSort(array, left, index - 1);
QuickSort(array, index + 1, right);
}
}
public static int partition(int[] array, int left, int right, int pivot) {
while (left < right) {
while (array[left] < pivot) {
left++;
}
while (array[right] > pivot) {
right--;
}
if (left < right) {
swap(array, left, right);
left++;
right--;
}
}
return left;
}
public static void swap(int[] array, int left, int right) {
int temp = array[left];
array[left] = array[right];
array[right] = temp;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(myArray));
QuickSort(myArray);
System.out.println(Arrays.toString(myArray));
}
}
However, this code gives me an incorrect result:
[35, 12, 25, 1, 5, 33, 56] - before sort
[1, 12, 25, 35, 5, 33, 56] - after sort
What do I have wrong here? I cannot find the flaw in the logic.
Multiple errors here,
You define pivot in main method, but quick sort algorithm will swap pivot from right element to the middle.
You edit left and right values in your while loop in a while loop, which result right and left to be smaller/taller than your pivot and skipping some swaps.
Here's the correct implementation without your while { while { ... } } and a correct pivot (from right to middle)
import java.util.Arrays;
public class Main
{
static int[] myArray = new int[] {35, 12, 25, 1, 5, 56, 33};
public static void QuickSort(int[] array) {
QuickSort(array, 0, array.length - 1);
}
public static void QuickSort(int[] array, int left, int right){
if(left < right) {
int index = partition(array, left, right);
QuickSort(array, left, index - 1);
QuickSort(array, index + 1, right);
}
}
public static int partition(int[] array, int left, int right){
int pivot = array[right];
int first = left - 1;
for (int j = left; j <= right - 1; j++) {
if(array[j] < pivot) {
first ++;
swap(array, first, j);
}
}
swap(array, first + 1, right);
return first + 1;
}
public static void swap(int[] array, int left, int right) {
int temp = array[left];
array[left] = array[right];
array[right] = temp;
}
public static void main(String[] args)
{
System.out.println(Arrays.toString(myArray));
QuickSort(myArray);
System.out.println(Arrays.toString(myArray));
}
}
Also you compare pivot which is an index with array[...] which is a value

Java and Python MergeSort

I am new to Java and I have been trying to do MergeSort, in a similar way I did it in Python.
This is how I do it in Python:
def merge_sort(a):
length = len(a)
if length > 1:
left = a[: len(a) // 2]
right = a[len(a) // 2 :]
merge_sort(left)
merge_sort(right)
merge(a, left, right)
def merge(a, left, right):
length = len(a)
left_half = len(left)
right_half = len(right)
i1, i2 = 0, 0
for i in range(length):
if i2 >= right_half or (i1 < left_half and left[i1] < right[i2]):
a[i] = left[i1]
i1 += 1
else:
a[i] = right[i2]
i2 += 1
This is my Java code and it returns index error.
import java.util.Arrays;
public class Merge_sort1 {
public static void main(String[] args) {
int[] a = {5, 3, 0, 1, 9, 6, 7, 4, 8, 2};
System.out.println("Array before sorting");
System.out.println(Arrays.toString(a));
mergeSort(a);
System.out.println("Array after sorting");
System.out.println(Arrays.toString(a));
}
public static void mergeSort(int[] a) {
if (a.length > 1) {
int mid = a.length / 2;
int[] left = Arrays.copyOfRange(a, 0, mid - 1);
int[] right = Arrays.copyOfRange(a, mid, a.length - 1);
mergeSort(left);
mergeSort(right);
merge(a, left, right);
}
}
public static void merge(int[] a, int[] l, int[] r) {
int i1 = 0;
int i2 = 0;
for(int i = 0; i < a.length; i++) {
if(i2 >= r.length || (i1 < l.length && l[i1] < r[i2])) {
a[i] = l[i1];
i1++;
a[i] = r[i2];
i2++;
}
}
}
}
I would really appreciate it if anyone can explain to me what I'm doing wrong and the best way to fix it.
Thank you
The copyOfRange call is erroneous; note that the second argument is exclusive rather than inclusive. Which means the second argument of the method minus 1 is the last element to be copied. So when calling copyOfRange(a, b, c) for example, the array a is copied from index b to c - 1, not c.
Also, the if statement in merge should be an if-else one (you forgot the else part).
So here is the code fixed, with proper output:
import java.util.Arrays;
public class Main {
public static void main(final String[] args) {
int[] a = {5, 3, 0, 1, 9, 6, 7, 4, 8, 2};
System.out.println("Array before sorting");
System.out.println(Arrays.toString(a));
mergeSort(a);
System.out.println("Array after sorting");
System.out.println(Arrays.toString(a));
}
public static void mergeSort(int[] a) {
if (a.length > 1) {
int mid = a.length / 2;
int[] left = Arrays.copyOfRange(a, 0, mid);
int[] right = Arrays.copyOfRange(a, mid, a.length);
mergeSort(left);
mergeSort(right);
merge(a, left, right);
}
}
public static void merge(int[] a, int[] l, int[] r) {
int i1 = 0;
int i2 = 0;
for(int i = 0; i < a.length; i++) {
if(i2 >= r.length || (i1 < l.length && l[i1] < r[i2])) {
a[i] = l[i1];
i1++;
}
else {
a[i] = r[i2];
i2++;
}
}
}
}

Median of medians select algorithm

for the last few days I've been trying really hard to write this algorithm but without success. The code works and most of the time it gives me the right result but there are some cases where it fails. For example with this array {3, 8, 1, 9, 10, 7, 6, 2, 5, 4} and k = 6 it should give me 6 as result but it gives me 7. Can someone help me? I can't figure out what's the problem.
Here is the code:
class MOMSelect {
static int median(int a[], int i, int n) {
if(i <= n)
Arrays.sort(a, i, n);
else
Arrays.sort(a, n, i);
return a[n/2];
}
static int medianOfMediansSelect(int a[], int left, int right, int k) {
int n = right - left + 1;
int i;
int[] medians = new int[(n + 4) / 5];
for (i = 0; i < n/5; i++) {
medians[i] = median(a, left + i * 5, 5);
}
if (i*5 < n) {
medians[i] = median(a,left + i * 5, n % 5);
i++;
}
int medianOfMedians = (i == 1)? medians[i - 1]: median(medians, 0, medians.length);
int pivotIndex = partition(a, left, right, medianOfMedians);
if (pivotIndex == k - 1) {
return a[pivotIndex];
}
else if (pivotIndex - left > k - 1) {
return medianOfMediansSelect(a, left, pivotIndex - 1, k);
}
else {
return medianOfMediansSelect(a, pivotIndex + 1, right, k);
}
}
static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static int partition(int[] a, int left, int right, int x) {
int i;
for (i = left; i < right; i++)
if (a[i] == x)
break;
swap(a, i, right);
i = left;
for (int j = left; j <= right - 1; j++) {
if(a[j] <= x) {
swap(a, i, j);
i++;
}
}
swap(a, i, right);
return i;
}
public static void main(String[] args) {
int a[] = {3, 8, 1, 9, 10, 7, 6, 2, 5, 4};
int n = a.length;
int k = 1;
System.out.println(medianOfMediansSelect(a, 0, n - 1, k));
}
}
Thanks in advance to everyone
Ok I solved. Further than my bad understanding of the Arrays.sort() method there was a stupid mistake on the if stucture where I check the pivotPosition value on the method medianOfMediansSelect()
More precisely on this line
else if (pivotIndex - left > k - 1) {
I should have done like this
else if (pivotIndex > k - 1) {
So, I modified your median method to correct the problem. You should check Arrays.sort method for a clear understanding.
Now it gives 6, for k=6.
Here is it,
static int median(int a[], int i, int n)
{
Arrays.sort(a, i, i + n - 1);
return a[i + n / 2];
}

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.

How do you perform a left shift on a circular array of ints?

Is there an existing method that performs a left shift on a circular array of ints?
Specifically, given an array with 4 items {1,2,3,4} and a shift amount of 2, I would like a method that shifts the first two letters to the back of the array, making it appear like so: {3,4,1,2}.
Would this algorithm work to shift a circular array by one?
algShiftByOne(Array)
{
temp=array[0];
i=1
while(i < Array.length - 1) // Loop from 1 up to array.length == last index
{
// If there is no exception i assume it copies value from
// initial array starting from 1 up to array.length
Array[i - 1] = Array[i];
i++;
}
Array[Array.length]=temp;
}
Here is my go at it... (here is an ideone.com demo)
import java.util.Arrays;
public class Test {
public static void circularShiftLeft(int[] arr) {
if (arr.length == 0)
return;
int first = arr[0];
System.arraycopy(arr, 1, arr, 0, arr.length - 1);
arr[arr.length - 1] = first;
}
public static void main(String[] arg) {
int[] arr = { 1, 2, 3, 4 };
System.out.println(Arrays.toString(arr));
circularShiftLeft(arr);
System.out.println(Arrays.toString(arr));
}
}
I had this one as an interview question. A simple in place (and somewhat intuitive) O(2n) solution for rotating m is to take the array, reverse it, then reverse the [0, m] and (m, n] subarrays. My solution, though a little less obvious, is inplace and O(n). Basically the idea is you rotate items forward one at a item, and eventually you will pass through all the elements. The catch is if the array is a multiple of the distance, which is where the GCD comes in. The following will do a rotate right, rotate left is left to the reader as an exercise:
public static void main(String[] args) {
int[] f = {0, 4, 8, 2, 6, 7, 4, 5, 3};
System.out.println(Arrays.toString(f));
rotate(f, 3);
System.out.println(Arrays.toString(f));
}
public static void rotate(int[] arr, int dist){
int tmp, tmp2, gcd = GCD(arr.length, dist);
for(int off=0;off<gcd;off++){
tmp = arr[off];
for(int i=0,idx=off;i<arr.length/gcd;idx=(idx+dist)%arr.length,i++){
tmp2 = arr[(idx+dist)%arr.length];
arr[(idx+dist)%arr.length] = tmp;
tmp = tmp2;
}
}
}
public static int GCD(int a, int b) {
if (b==0) return a;
return GCD(b,a%b);
}
Assuming that you want to shift by n:
Copy the first n elements in an array named , for example, tempNumbers
For each element from n to the last one, shift it to the left by n
Copy the elements from tempNumbers to the end of the original array
Why don't you use a circular (doubly) linked list? In that case you only have to change your 'start pointer'.
Here is some pseudo-code to do what you want.
Array shift(Array a, int shiftLength) {
Array b;
for(i = shiftLength; i < a.size(); i++)
b.add(a.at(i));
for(i = 0; i < shiftLength; i++)
b.add(a.at(i));
return b;
}
This would shift the array a one to the left.
int[] a = new int[] { 1, 2, 3, 4, 5 };
int[] b = new int[a.length];
System.arraycopy(a, 1, b, 0, a.length - 1);
b[a.length - 1] = a[0];
// b = {2,3,4,5,1}
// edit
a = b;
public static void shift(int[] arr, int offs) {
// e.g. arr = 1,2,3,4,5,6,7,8,9; offs = 3
offs %= arr.length;
offs = offs < 0 ? arr.length + offs : offs;
if (offs > 0) {
// reverse whole array (arr = 9,8,7,6,5,4,3,2,1)
for (int i = 0, j = arr.length - 1; i < j; i++, j--)
swap(arr, i, j);
// reverse left part (arr = 7,8,9,6,5,4,3,2,1)
for (int i = 0, j = offs - 1; i < j; i++, j--)
swap(arr, i, j);
// reverse right part (arr = 7,8,9,1,2,3,4,5,6)
for (int i = offs, j = arr.length - 1; i < j; i++, j--)
swap(arr, i, j);
}
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}

Categories