I have problem with sort the matrix. [MergeSort] - java

Displays the list of matrix columns on the screen, in descending order of the maximum in the respective columns; data sorting will be done through merge sort.
I write the maximal elements in the vector, then the vector is sorted, and already from the vector you have to display the columns. And if there are 2 identical numbers in the matrix, it has to display the correct column, it must work with coordinates, but I failed.
2 6 1
10 5 11
4 8 9
Final result
1 2 6
11 10 5
9 4 8
static void maxVec(int[][] myArray, int n, int m) {
int[] elMax=new int[m];
for (int i=0; i<m; i++) {
int max=0;
if(n>m) {
int count=(n-m);
for (int j=0; j<myArray[i].length+count; j++) {
if(myArray[j][i]>max) {
max=myArray[j][i];
}
}
}
if(n==m) {
for (int j=0; j<myArray[i].length; j++) {
if(myArray[j][i]>max) {
max=myArray[j][i];
}
}
}
if(n<m) {
int count=(m-n);
for (int j=0; j<m-count; j++) {
if(myArray[j][i]>max) {
max=myArray[j][i];
}
}
}
elMax[i]=max;
}
mergeSort(elMax, elMax.length);
for(int i=0;i<elMax.length;i++) {
System.out.print(elMax[i]+" ");
}
System.out.println("\n===================================");
//here i don't know what to do
for(int k=0;k<elMax.length;k++) {
for (int i=0; i<myArray.length; i++) {
for (int j=0; j<myArray[i].length; j++) {
if(elMax[k]==myArray[i][j]) {
for (int w=0; w<myArray[w].length; w++) {
System.out.print(myArray[i][w]+" ");
}
System.out.println();
}
}
}
}
}
//merge sort
public static void merge(
int[] a, int[] l, int[] r, int left, int right) {
int i=0, j=0, k=0;
while(i<left && j<right) {
if(l[i]>=r[j]) {
a[k++]=l[i++];
}
else {
a[k++]=r[j++];
}
}
while(i<left) {
a[k++]=l[i++];
}
while(j<right) {
a[k++]=r[j++];
}
}
public static void mergeSort(int[] a, int n) {
if(n<2) {
return;
}
int mid =n/2;
int[] l = new int[mid];
int[] r = new int[n-mid];
for(int i=0;i<mid;i++) {
l[i]=a[i];
}
for(int i=mid;i<n;i++) {
r[i-mid]=a[i];
}
mergeSort(l, mid);
mergeSort(r, n-mid);
merge(a, l, r, mid, n-mid);
}

hope this helps you, and better use this on not very large matrix,
class Matrix {
int[][] matrix = new int[][] {
{ 1, 3, 5, 16, 9},
{ 2, 4, 15, 6, 0},
{18, 14, 17, 11, 10},
{14, 15, 12, 16, 13}
};
void sortByColumn() {
class ColMax {
int col;
int val;
ColMax(int c, int v) {
col = c;
val = v;
}
#Override
public String toString() {
return "[" + col + ": " + val + "]";
}
}
int cols = matrix[0].length;
int rows = matrix.length;
int[][] target = new int[rows][cols];
ColMax[] colmaxes = new ColMax[cols];
for (int i = 0; i < cols; i++) {
colmaxes[i] = new ColMax(i, matrix[0][i]);
}
// find every column's max item
for (int i = 0; i < cols; i++) {
for (int k = 0; k < rows; k++) {
if (colmaxes[i].val < matrix[k][i]) {
colmaxes[i].val = matrix[k][i];
}
}
}
// sort it descending
Arrays.sort(colmaxes, (a,b) -> b.val - a.val);
for (int i = 0; i < cols; i ++) {
System.out.print(colmaxes[i] + ", ");
}
System.out.println();
// copy sorted cols
for (int i = 0; i < rows; i++) {
for (int k = 0; k < cols; k++) {
target[i][k] = matrix[i][colmaxes[k].col];
System.out.print(target[i][k] + ", ");
}
System.out.println();
}
}
}

Related

Need help to understand an implementation of the Counting Sort sort algorithm

This code is about algorithms and datastructures. This code runs perfectly and i just have some questions on it because it seems like i don't understand two points. So my questions for that is:
which informations are in the countingArray?
how often is the while loop executed?
public class CountingSort {
public static void main(String[] args) {
int[] m1 = { 1, 17, 3, 1, 4, 9, 4, 4 };
System.out.println("unsorted:");
output(m1);
int min1 = rangeMin(m1);
int max1 = rangeMax(m1);
countingSort(m1, min1, max1);
System.out.println("sorted:");
output(m1);
int[] m2 = { -1, 13, 3, -1, -4, 9, -4, 4 };
System.out.println("unsorted:");
output(m2);
int min2 = rangeMin(m2);
int max2 = rangeMax(m2);
countingSort(m2, min2, max2);
System.out.println("sorted:");
output(m2);
}
public static void output(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + ", ");
}
System.out.println();
}
public static int rangeMin(int[] a) {
int minimum = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] < minimum)
minimum = a[i];
}
return minimum;
}
public static int rangeMax(int[] array) {
int maximum = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > maximum)
maximum = array[i];
}
return maximum;
}
public static void countingSort(int[] array, int rangeMin, int rangeMax) {
int[] countingArray = new int[rangeMax - rangeMin + 1];
for (int i : array) {
countingArray[i - rangeMin]++;
}
int c = 0;
for (int i = rangeMin; i <= rangeMax; i++) {
while (countingArray[i - rangeMin] > 0) {
array[c] = i;
c++;
countingArray[i - rangeMin]--;
}
}
}
}
CountingSort has O(n) time and space complexity. You iterate (i.e. use for loop) twice.
public class CountingSort {
public static void main(String... args) {
proceed(1, 17, 3, 1, 4, 9, 4, 4);
System.out.println("---");
proceed(-1, 13, 3, -1, -4, 9, -4, 4);
}
public static void proceed(int... arr) {
System.out.print("unsorted: ");
print(arr);
countingSort(arr);
System.out.print("sorted: ");
print(arr);
}
public static void print(int... arr) {
System.out.println(Arrays.stream(arr)
.mapToObj(i -> String.format("%2d", i))
.collect(Collectors.joining(",")));
}
public static void countingSort(int... arr) {
int min = Arrays.stream(arr).min().orElse(0);
int max = Arrays.stream(arr).max().orElse(0);
// contains amount of number in the unsorted array
// count[0] - amount of min numbers
// count[count.length - 1] - amount of max numbers
int[] count = new int[max - min + 1];
for (int i : arr)
count[i - min]++;
// fill source array with amount of numbers
for (int i = 0, j = 0; i < count.length; i++)
for (int k = 0; k < count[i]; k++, j++)
arr[j] = min + i;
}
}

Index out of bounds Java merge sort?

I am working on a merge sort algorithm. Below is what i have written so far. The problem is when I try and run it to see if it is working I get the index out of bounds error on the if statement I marked with a comment.
Why am I getting index out of bounds on the line I commented next to?
I know what the error means but am unable to decipher why its out of bounds.
public class MergeSort {
public static int mergeSort(int[] list1, int[] list2) {
int[] list3 = new int[list1.length + list2.length];
int smallest1 = list1[0];
int smallest2 = list2[0];
int position1 = 0;
int position2 = 0;
for (int i = 0; i<list1.length + list2.length; i++) {
for (int j =0; j<= list1.length; j++) {
if (list1[j] < smallest1) { //here index out of bouds
smallest1 = list1[j];
System.out.print(list1[j]+"smallest value");
position1 = j;
}
}
for (int l =0; l<= list2.length; l++) {
if (list2[l] < smallest2) {
smallest2 = list2[l];
System.out.print(list2[l]+"smallest value");
position2 = l;
}
}
if (smallest1< smallest2) {
list3[i] = smallest1;
} else if (smallest2< smallest1) {
list3[i] = smallest2;
}
}
//print the array
for (int l =0; l<= list2.length; l++) {
System.out.print("new array 3" + list3[l]);
}
return 1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] list1 = {17, 22, 35, 42, 60};
int[] list2 = {9, 14, 66};
int[] list3;
mergeSort(list1, list2);
}
}
Indexes run from 0, this means when list1.length = 5 then the index can be 0 through 4
change
for (int j =0; j<= list1.length; j++)
to
for (int j =0; j < list1.length; j++)
This is because your for loop condition is <=. Try to use <

Algorithm for combinations of integer in an array

I am having difficulties for writing an algorithm that will create an array of arrays, from a single array of integers.
Say, I have an
int[] intArray = new int[] {1,2,3,4,5};
What I need from it is an array of an arrays that will look like this:
int[][] array = new int[][]{
{-1,2,3,4,5},
{1,-2,3,4,5},
{1,2,-3,4,5},
{1,2,3,-4,5},
{1,2,3,4,-5};
Thank you in advance!!
EDIT:
The following code works for the case if I want to have only one negative value. How about if I would like to have 2,3,4... negative values? Is there a way to make it more dynamic? For example, from {1,2,3,4,5}; to get: {-1,-2,3,4,5}, {-1,2,-3,4,5}, {-1,2,3,-4,5}, {-1,2,3,4,-5}, {1,-‌​2,-3,4,5},{1,-2,3,-4‌​,5}, {1,-2,3,4,-5}...‌​. or for 3 negative values: {-1,-2,-3,4,5}, {-1,-2,3,-4,5}, {-1,-2,3,4,-5}, {1,-2,-3,-4,5},‌ ​{1,-2,-3,4,-5}, {1,2,‌​-3,-4,-5}...etc I hope you get my point! Thanks again guys!!
You could try this:
int l = intArray.length;
int[][] newArray = new int[l][l];
for (int i = 0; i < l; i++) {
for (int j = 0; j < l; j++) {
newArray[i][j] = j == i ? intArray[j] * -1 : intArray[j];
}
}
newArray will have the values you are expecting.
how about
public class x
{
public static int[][] convert(int in[])
{
int s = in.length;
int out[][] = new int[s][s];
for (int i = 0; i < s; ++i) { // row loop
for (int j = 0; j < s; ++j) {
if (i == j)
out[i][j] = -in[j];
else
out[i][j] = in[i];
}
}
return out;
}
public static void print(int in[][])
{
for (int i = 0; i < in.length; ++i) {
String sep = "";
for (int j = 0; j < in[i].length; ++j) {
System.out.print(sep + in[i][j]);
sep = ", ";
}
System.out.println("");
}
}
public static void main(String argv[])
{
int in[] = { 1, 2, 3, 4, 5 };
int out[][];
out = convert(in);
print(out);
}
}
int[] intArray = new int[] {1,2,3,4,5};
int algoIntArray[][] = new int[intArray.length][intArray.length];
for(int i = 0; i < intArray.length; i++){
for (int j = 0; j < algoIntArray[i].length; j++){
if (i == j){
algoIntArray[i][j] = -intArray[j];
} else {
algoIntArray[i][j] = intArray[j];
}
}
}
This code will work for you!

Swap rows in 2d array by row sum in Java

I implemented this thing but I am not sure this is correct
Example : int [][]={{2,1,0},{2,8,9},{1,1,0}}
In the above sum of elements in row 1 (2+1+0=3) is lesser than sum of elements in row 2(2+8+9=19) and greater than row 3 sum(2).
The final array should be like {{2,8,9},{2,1,0},{1,1,0}}
int arr[5][5];
int rowSum[5];
int sum = 0;
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
sum = sum + arr[i][j];
}
rowSum[i] = sum;
sum=0;
}
int swap;
//now sorting
for (int c = 0 ; c < ( n - 1 ); c++)
{
for (int d = 0 ; d < n - c - 1; d++)
{
if (rowSum[d] > rowSum[d+1]) /* For decreasing order use < */
{
swap = rowSum[d];
rowSum[d] = rowSum[d+1];
rowSum[d+1] = swap;
//swapping original array
for(int i=0;i<5;i++){
swap = arr[d][i];
arr[d][i] = arr[d+1][i];
arr[d+1][i] = swap;
}
}
}
}
Using Java 8 features:
int[][] arr = { { 2, 1, 0 }, { 2, 8, 9 }, { 1, 1, 0 } };
Arrays.sort(arr, Comparator.comparingInt((int[] row) -> Arrays.stream(row).sum()).reversed());
System.out.println(Arrays.deepToString(arr));
Integer[][] numbers = new Integer[][]{{2,1,0},{2,8,9},{1,1,0}};
System.out.println("Before:");
for(Integer[] row : numbers) {
for(Integer num : row) {
System.out.print(num+",");
}
System.out.println("");
}
Arrays.sort(numbers, new Comparator<Integer[]>(){
#Override
public int compare(Integer[] o1, Integer[] o2) {
Integer sumArray_1 = 0;
Integer sumArray_2 = 0;
for(int i = 0; i < o1.length; ++i) {
sumArray_1 += o1[i];
}
for(int i = 0; i < o2.length; ++i) {
sumArray_2 += o2[i];
}
return sumArray_2.compareTo(sumArray_1); //Decending order
}
});
System.out.println("After:");
for(Integer[] row : numbers) {
for(Integer num : row) {
System.out.print(num+",");
}
System.out.println("");
}
Output:
Before:
2,1,0,
2,8,9,
1,1,0,
After:
2,8,9,
2,1,0,
1,1,0,
Use the below Code Snippet,
int[][] temp = {{2,1,0},{2,8,9},{1,1,0}};
Arrays.sort(temp, new Comparator<int[]>() {
#Override
public int compare(int[] a, int[] b) {
return Integer.compare(b[1], a[1]);
}
});
System.out.println("After applying comparator");
for(int[] arr:temp){
for(int val:arr){
System.out.print(val+" ");
}
System.out.println("");
}
It will display the output like this,
After applying comparator
2 8 9
2 1 0
1 1 0

Swapping two elements in an array

I'm doing mooc.fi, my code works but it won't submit.
errors I'm getting
the method swap does not work correctly with parameter 4, 7, 8, 6 index1=0 index2=3
the result was 4, 7, 8, 6 but it should have been 6, 7, 8, 4
and
the method sort does not work correctly with parameter 10, 20, 6, -1, 13, 11
the result was 10, 20, 6, -1, 13, 11 but it should have been -1, 6, 10, 11, 13, 20
I know the errors are connected but I'm not too sure what to do to fix this, any help is appreciated! thank you!
My Code:
import java.util.Arrays;
public class Main {
public static int smallest(int[] array) {
int start = array[0];
for (int i = 0; i < array.length; i++) {
if (array[i] < start) {
start = array[i];
}
}
return start;
}
public static int indexOfTheSmallest(int[] array) {
for (int i = 0; i < array.length; i++) {
if (array[i] == smallest(array)) {
return i;
}
}
return 0;
}
public static int indexOfTheSmallestStartingFrom(int[] array, int index) {
int minIndex = index;
for (int i = index; i < array.length; i++) {
if (array[i] < array[minIndex]) {
minIndex = i;
}
}
return minIndex;
}
public static void swap(int[] array, int index1, int index2) {
int hold = 0;
for (int i = 0; i < array.length; i++) {
hold = array[index1];
array[index1] = array[index2];
array[index2] = hold;
}
}
public static void sort(int[] array) {
System.out.println(Arrays.toString(array));
for (int i = 0; i < array.length; i++) {
swap(array, i, indexOfTheSmallestStartingFrom(array, i));
System.out.println(Arrays.toString(array));
}
}
public static void main(String[] args) {
int[] values = {8, 5, 3, 7, 9, 6, 1, 2, 4};
sort(values);
}
}
This algorithm is designed very badly. both smallest and indexOfSmallest use a loop, this will degrade geometrically.
The swap should not be scanning the entire array as you only want to swap two elements, not all of them!
You're effectively doing a whack version of a bubble-sort, but in a really convoluted way with too many loops. This will start to perform horribly with any decent sized list.
A much simpler version can be found here
You do not need a loop for the swap method. As you only want to change the two element once and not n-times (which results in not swapping them at all if n is an even number).
public int[] swapArrayElement(int arr[], int a, int b) {
int index1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == a || arr[i] == b) {
index1 = i;
if (arr[i] == a) {
for (int k = index1; k < arr.length; k++) {
if (arr[k] == b) {
arr[k] = arr[index1];
arr[index1] = b;
}
}
return arr;
} else if (arr[i] == b) {
{
for (int k = index1; k < arr.length; k++) {
if (arr[k] == a) {
arr[k] = arr[index1];
arr[index1] = a;
}
}
}
return arr;
}
}
}
return arr;
}

Categories

Resources