Median of medians select algorithm - java

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

Related

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

Data Structures

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.

What's wrong with my HeapSort code?

I'm attempting to write a heapsort method in java but it's not working exactly as I want it to:
public class HeapSort {
private static int n;
private static void swap(int[] A, int a, int b)
{
int tmp = A[a];
A[a] = A[b];
A[b] = tmp;
}
private static void insert(int[] A, int i)
{
int left = i * 2;
int right = left + 1;
int max = i;
if (left <= n && A[left] < A[max]){
max = left;
}
if (right <= n && A[right] > A[max]) {
max = right;
}
if (max != i) {
swap(A, i, max);
insert(A, max);
}
}
public static void HeapSort(int[] A)
{
n = A.length - 1;
for (int i = n / 2; i >= 0; i--)
insert(A, i);
for (int i = n; i > 0; i--) {
swap(A, 0, i);
n--;
insert(A, 0);
}
}
public static void main(String[] args){
int[] A = new int[] {9, 2, 8, 1, 4};
System.out.println(java.util.Arrays.toString(arr));
HeapSort(A);
System.out.println(java.util.Arrays.toString(arr));
}
}
It works with some arrays however arrays like 9, 2, 8, 1, 4 will get sorted into 1, 4, 2, 8, 9. So why isn't it sorting the array in the correct way?
if (left <= n && A[left] > A[i]){
max = left;
}
Try this and see.
I have made the complete program as below. This works fine for input you provided.
public class HeapSort {
private static int n;
private static void swap(int[] A, int a, int b)
{
int tmp = A[a];
A[a] = A[b];
A[b] = tmp;
}
private static void insert(int[] A, int i)
{
int left = i * 2;
int right = left + 1;
int max = i;
if (left <= n && A[left] > A[i]){
max = left;
}
if (right <= n && A[right] > A[max]) {
max = right;
}
if (max != i) {
swap(A, i, max);
insert(A, max);
}
}
public static void HeapSort(int[] A)
{
n = A.length - 1;
for (int i = n / 2; i >= 0; i--)
insert(A, i);
for (int i = n; i > 0; i--) {
swap(A, 0, i);
n--;
insert(A, 0);
}
}
public static void main(String[] args){
int[] A = new int[] {19, 6, 28, 1, 0};
int[] B = new int[] {1, 2, 4, 8, 9, 0};
System.out.println(java.util.Arrays.toString(A));
System.out.println(java.util.Arrays.toString(B));
HeapSort(A);
HeapSort(B);
System.out.println(java.util.Arrays.toString(A));
System.out.println(java.util.Arrays.toString(B));
}
}
Here is the output.
[19, 6, 28, 1, 0]
[1, 2, 4, 8, 9, 0]
[0, 1, 6, 19, 28]
[0, 1, 2, 4, 8, 9]
If you define left = i * 2, the root of your heap should be stored in A[1], not A[0]. By not using the array at index 0, you can always say that the left and right children of a node i are 2*i and 2*i+1, respectively.
Basically, in your HeapSort, you should change 0 to 1 (there are 4 of them). Test it with array {0, 9, 2, 8, 1, 4}.
And also, a comparison in insert is also wrong. It should be A[left] > A[max].

Sorting index of array using merge Sort

I was trying to sort the index of an array using mergesort. The mergesort works perfectly , and the final answer is exactly correct but I am not sure why the indexes do not work out in correct positions. I do not want to sort the array, all I want to do is sort the perm[] array which is the index list.
To avoid confusions, Heres an example:
perm array holds the initial indices of the original array nums[] (i.e. 0 to nums.length - 1)
I want to move the indices in the perm array based on the data in the nums[] array such that the indices represent the sorted order.
For example :
Array -> (-1,9,-5,3,0)
Initial perm -> (0,1,2,3,4)
After sorting perm based on array - > (2,0,4,3,1)
Here's my code:
import java.util.Arrays;
public class IndexSort {
public boolean leq(Comparable u, Comparable v) {
return u.compareTo(v) <= 0;
}
public void merge(Comparable a[], int temp[], int perm[], int lo, int mid, int hi) {
int i = lo, j = mid + 1;
for (int k = lo; k <= hi; k++) {
temp[k] = perm[k];
}
for (int k = lo; k <= hi; k++) {
if (i > mid) {
perm[k] = temp[j++];
} else if (j > hi) {
perm[k] = temp[i++];
} else if (leq(a[perm[i]], a[perm[j]])) {
perm[k] = temp[i++];
} else {
perm[k] = temp[j++];
}
}
}
public void mergeSort(Comparable a[], int temp[], int perm[], int lo, int hi) {
if (hi <= lo)
return;
int mid = (hi + lo) / 2;
mergeSort(a, temp, perm, lo, mid);
mergeSort(a, temp, perm, mid + 1, hi);
merge(a, temp, perm, lo, mid, hi);
System.out.println(" lo = " + lo + " mid = " + mid + " hi = " + hi);
System.out.println(Arrays.toString(perm));
}
public void indexSort(Comparable nums[], int perm[]) {
int temp[] = new int[nums.length];
Comparable temp2[] = new Comparable[nums.length];
mergeSort(nums, temp, perm, 0, nums.length - 1);
}
public static void main(String[] args) {
IndexSort o1 = new IndexSort();
Comparable nums[] = { 12, -12, 0, 123, -123, 1, 2, 3, 4, -4, -4, -3, -2, 1 };
int perm[] = new int[nums.length];
for (int i = 0; i < perm.length; i++) {
perm[i] = i;
}
System.out.println(Arrays.toString(nums));
System.out.println(Arrays.toString(perm));
o1.indexSort(nums, perm);
System.out.println(Arrays.toString(perm));
}
}
I think this line needs to change from perm to temp:
} else if (leq(a[temp[i]], a[temp[j]])) {

Quick sort Error java

public int partition(int[]a,int i,int j){
int x=a[i];
int c=i;
for (int d = c+1; d < j; d++) {
if (a[d]<=x) {
c=c+1;
exchange(a, c, d);
}
}
exchange(a, c, i);
return c;
}
public void exchange(int[]a,int c,int d){
int temp=a[c];
a[c]=a[d];
a[d]=temp;
}
public void sort(int[]a,int i,int j){
int index;
if(i<j){
index=partition(a, i, j);
sort(a, i, index-1);
sort(a,index+1, j);
}
}
**strong text**public static void main(String[] args) {
// TODO code application logic here
QUICKSORT abir=new QUICKSORT();
abir.PRINT(abir.a);
abir.sort(abir.a, 0,10);
abir.PRINT(abir.a);
}
Here is my QuickSort code.
If i enter [6 10 13 5 8 3 2 11]
it prints [2 5 3 6 8 11 10 13]
Can anyone explain whats wrong with my code???
THank you
Your code seems quite strange to me, where did you take that?
Anyway why don't you take a look at this page for an explanation of quick sort?
http://www.algolist.net/Algorithms/Sorting/Quicksort
int partition(int arr[], int left, int right)
{
int i = left, j = right;
int tmp;
int pivot = arr[(left + right) / 2];
while (i <= j) {
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
};
return i;
}
void sort(int arr[], int left, int right) {
int index = partition(arr, left, right);
if (left < index - 1)
sort(arr, left, index - 1);
if (index < right)
sort(arr, index, right);
}
static int[] a = {6, 10, 13, 5, 8, 3, 2, 11};
public static void main(String[] args) {
// TODO code application logic here
QUICKSORT abir=new QUICKSORT();
System.out.println(Arrays.toString(a));
abir.sort(a, 0, 7);
System.out.println(Arrays.toString(a));
}

Categories