How to group the rows from a multidimensional array of numbers? - java

I've been trying to sort this multidimensional array without using array.sort
int arg[][] = {
{26, 39, 3, 13},
{22, 97, 17, 123},
{46, 19, 63, 123},
{1, 37, 90, 32},
{17, 37, 90, 32}};
Into this
int arg[][] = {
{3, 13, 26, 39},
{17,22,97,123},
{19, 46, 63, 123},
{1, 32, 37, 90},
{17, 32, 37, 90}};
It sorts the rows from the lowest number to the highest.
Using a bubble sort, I have tweaked this code and done everything but it only sorts the first 3 rows and it and throws an out of bound error.
This is the code I have
for (int i = arg[0].length - 1; i >= 0; i--) {
for (int j = 0; j < i ; j++) {
for (int k = 0; k < i ; k++) {
if (arg[k][j] > arg[k][j + 1]) {
int temp = arg[k][j];
arg[k][j] = arg[k][j + 1];
arg[k][j + 1] = temp;
}
}
}
}
for (int i = 0; i < arg.length; i++) {
for (int j = 0; j < arg[i].length; j++) {
System.out.print(arg[i][j] + " ");
}
System.out.println();
}
What am I doing wrong?

As you said last 2 rows are not sorted.I print out your indexces that you are iterating over which showed me that you dint reach to last 2 rows .Instead you can do
for (int i = arg[0].length - 1; i >= 0; i--) {
for (int j = 0; j < arg.length; j++) {
for (int k = 0; k < arg[j].length - 1; k++) {
if (arg[j][k] > arg[j][k + 1]) {
int temp = arg[j][k];
arg[j][k] = arg[j][k + 1];
arg[j][k + 1] = temp;
}
}
}
}
Demo

Why is i used a the stopping condition on the sort loops. Couldn't it be something like arg [i].length, as follows.
for (int i = arg[0].length - 1; i >= 0; i--) {
for (int j = 0; j < arg [i].length; j++) {
for (int k = 0; k < arg [i].length ; k++) {
if (arg[i][j] > arg[i][k]) {
int temp = arg[i][j];
arg[i][j] = arg[i][k];
arg[i][k] = temp;
}
}
}
}
for (int i = 0; i < arg.length; i++) {
for (int j = 0; j < arg[i].length; j++) {
System.out.print(arg[i][j] + " ");
}
System.out.println();
}
Otherwise on the 5th element i = 4 but there are only 4 elements in each inner array so the maximum valid index is 3

Classic Implementation of Bubble Sort
private static void bubblesort(Integer[] array) {
for (int i = 0; i < array.length; i++) {
for(int j = 0; j < array.length - 1; j++) {
if(array[j].compareTo(array[j+1]) > 0) {
swap(j, j+1, array);
}
}
}
}
private static void swap(Integer index1, Integer index2, Integer[] array) {
if(index1 == index2)return;
Integer temp = new Integer(array[index2]);
array[index2] = array[index1];
array[index1] = temp;
}

Related

Removing a redundant variable/shortening code

I need to remove the "min" variable and still allow the sorting program to run however, I am confused on where exactly to start.
int[] A = {13, 5, 2, 0, 3, 1, 21, 1, 8};
for (int k=0; k<A.length-1; k++) {
int min = A[k];
int minPosition = k;
for (int i=k+1; i<A.length; i++) {
if (A[i] < min) {
min = A[i];
minPosition = i;
}
}
int temp = A[k];
A[k] = A[minPosition];
A[minPosition] = temp;
}
for (int i=0; i<A.length; i++) {
System.out.println (A[i]);
}
You have both min and minPosition:
int min = A[k];
int minPosition = k;
Start by removing the declaration for min altogether (delete the line int min = A[k]), delete the line min = A[i], and finally, edit the if statement from this:
if (A[i] < min) {
...
}
to this:
if (A[i] < A[minPosition]) {
...
}
You have 2 variables that are doing the same job :
i) min which keeps track of the minimum in the array
ii) minPosition which is index of the min value.
You can simply compare everytime with the element at minPosition and swap it in the end.
class Main {
public static void main(String args[]) {
int[] A = { 13, 5, 2, 0, 3, 1, 21, 1, 8 };
for (int k = 0; k < A.length - 1; k++) {
// int min = A[k];
int minPosition = k;
for (int i = k + 1; i < A.length; i++) {
if (A[i] < A[minPosition]) {
minPosition = i;
}
}
int temp = A[k];
A[k] = A[minPosition];
A[minPosition] = temp;
}
// for (int i = 0; i < A.length; i++) {
System.out.println(Arrays.toString(A));
// }
}
}

How to shift elements to left after removing array element?

I was asked to write, to remove the element (lets say k=30) from the array and shift the other elements to its left without using inbuilt methods.
I have tried the below approach.
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = new int[] { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int count = 0;
System.out.println("---Original Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k)
count++;
}
for (int j = 0; j < count; j++) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k) {
for (int l = i; l < arr.length - 1; l++) {
arr[l] = arr[l + 1];
}
}
}
}
System.out.println("---Modified Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
I need output like this: [1 2 4 5 6 0 0]
But the output from the above logic is: [1 2 4 5 6 6 6]
Also, I'm worried about using nested for loops here. Is there any way that we can reduce the time complexity with out using any inbuilt methods?
Here is another variant:
int[] arr = new int[] { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int j = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != k) {
arr[j++] = arr[i];
}
}
while (j < arr.length) {
arr[j++] = 0;
}
In order to not change your approach drastically, I would suggest adding another iteration of the array at the end, to insert 0s to count-many indices from the end of your array.
This would be as simple as adding the following snippet:
// nested for loop
// ...
// set trailing elements to 0s
for (int i = 0; i < count ; i++)
arr[arr.length-1-i] = 0;
System.out.println("\n---Modified Array------");
// ...
There are some cleaner/more-efficient ways of solving this problem.
Based exactly on your approach, I went ahead and made a modification to your nested loop to not require another iteration.
for (int j = 0; j < count; j++) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k) {
for (int l = i; l < arr.length - 1; l++)
arr[l] = arr[l + 1];
// since we have performed the shifting, we can safely set the last element to 0
arr[arr.length-1] = 0; // <----- this was missing!!
}
}
}
The following code gives the desired result:
int [] arr = { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int elementCount = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k) {
++elementCount;
}
}
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k) {
count++;
for (int j = i; j < arr.length-1; j++) {
arr[j] = arr[j+1];
}
arr[arr.length-1] = 0;
}
if (count == elementCount) {
break;
}
}
I don't know if it helps. This is a simplified aproach, that is easier to read and understand(at least for people that learned C), that does removal as required....
public static void main(String[] args) {
int[] arr = new int[] { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int i=0;
int j=0;
for(;j<arr.length;i++,j++){
if((arr[i]=arr[j])==k) i--;
}
while(i<j)arr[i++]=0;
System.err.println(Arrays.toString(arr));
}
output:[1, 2, 4, 5, 6, 0, 0]
First version with a small fix on your code. You issue is that the shifted elements need to be replaced by zero. Which require basically an if statement with the arr.length - count
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = new int[] { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int count = 0;
System.out.println("---Original Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k)
count++;
}
for (int j = 0; j < count; j++) {
for (int i = 0; i < arr.length; i++) {
if(i >= arr.length - count){
arr[i] = 0;
}else {
if (arr[i] == k) {
for (int l = i; l < arr.length - 1; l++) {
arr[l] = arr[l + 1];
}
}
}
}
}
System.out.println("---Modified Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
}
Which gives output
---Original Array------
1 2 30 4 5 30 6
---Modified Array------
1 2 4 5 6 0 0
Now, we can simplify the code also
public static void main(String[] args) {
int[] arr = new int[] { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int count = 0;
System.out.println("---Original Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
for(int i = 0; i < arr.length; i++){
if(arr[i]==k){
count++;
}else{
arr[i-count] = arr[i];
}
}
for(int i = 1; i <= count; i++){
arr[arr.length - i] = 0;
}
System.out.println("---Modified Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
}
which give the same output

Bubble Sort is returning the same array again?

Can someone explain why this bubble sort is not working in my code. I would think this would sort easily. Maybe not all correctly but still somewhat sorting but instead it just returns the same array?
import java.util.Random;
public class Sorts {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Set array to be sorted length here!
int listLength = 20;
//Declares Array
int[] toBeSortedArray = new int[listLength];
int[] sortedArray = new int[listLength];
//fills Array with random numbers
for (int i = 0; i < listLength; i++)
{
Random rand = new Random();
toBeSortedArray[i] = rand.nextInt(100);
}
//Passing toBeSortedArray to function
sortedArray = SwapSort(toBeSortedArray, listLength);
//Testing the filling of Array - *hint* select all comment lines and select "Toggle Block Comment"
for (int i = 0; i <listLength; i++)
{
System.out.print(toBeSortedArray[i] + ", ");
}
System.out.println();
for (int i = 0; i <listLength; i++)
{
System.out.print(sortedArray[i] + ", ");
}
}
public static int[] SwapSort(int[] array, int length)
{
int temp;
for (int i = 0; i < length; i++)
{
for (int j = 1; j < length - 1; j++)
{
if (array[i] > array[j])
{
temp = array[i];
array[i] = array[j+1];
array[j+1] = temp;
}
}
}
return array;
}
}
Output:
55, 42, 50, 48, 9, 38, 84, 10, 81, 24, 5, 18, 32, 74, 2, 89, 15, 84, 84, 45,
55, 42, 50, 48, 9, 38, 84, 10, 81, 24, 5, 18, 32, 74, 2, 89, 15, 84, 84, 45,
Three things
First, you are swapping the wrong elements.
if (array[i] > array[j]) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
You must swap the elements array[i] and array[j]
Second
Your inner loop starts must start with j = i + 1 and not 1 and should go upto length.
Third
Since you are printing both the arrays in your code after calling the function, both will give the same output since, java passes the array by reference and your original array also gets modified. So even if swapping was happening in your original code, you got the same output
Full code
class Sorts {
public static void main(String[] args) {
//Set array to be sorted length here!
int listLength = 20;
//Declares Array
int[] toBeSortedArray = new int[listLength];
int[] sortedArray = new int[listLength];
//fills Array with random numbers
for (int i = 0; i < listLength; i++) {
Random rand = new Random();
toBeSortedArray[i] = rand.nextInt(100);
}
for (int i = 0; i < listLength; i++) {
System.out.print(toBeSortedArray[i] + ", ");
}
//Passing toBeSortedArray to function
sortedArray = SwapSort(toBeSortedArray, listLength);
}
public static int[] SwapSort(int[] array, int length) {
int temp;
for (int i = 0; i < length; i++) {
for (int j = 1; j < length; j++) {
if (array[i] > array[j]) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
System.out.println("");
for (int i = 0; i < length; i++) {
System.out.print(array[i] + ", ");
}
System.out.println();
return array;
}
}
Your inner loop in SwapSort should start with int j = i + 1; j < length (and i < length - 1 in the outer loop), think about what happens when j is 1 and i is 2 in your algorithm. Also, your swap should occur on the elements you are comparing. Like,
public static int[] SwapSort(int[] array, int length) {
int temp;
for (int i = 0; i < length - 1; i++) {
for (int j = i + 1; j < length; j++) {
if (array[i] > array[j]) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
return array;
}

how to count and print out only duplicates?

I know how to go through whole array, but I only need number of duplicate occurrences. I'm at beginners level, so just basic use of loops and arrays.
int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
for (int i = 0; i < array.length; i++) {
int count = 0;
for (int j = 0; j < array.length; j++) {
count++;
}
System.out.println(array[i] + "\toccurs\t" + count + "X");
}
You can do better if you use more than just loops and arrays, but a simple algorithm would be to use two nested for loops, and put an if statement inside that increments a counter when a duplicate is found.
int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
for (int i = 0; i < array.length - 1; i++) {
int count = 1;
for (int j = i + 1; j < array.length; j++) {
if (array[i] == array[j]) {
count++;
}
}
if (count > 1) {
System.out.println(array[i] + "\toccurs\t" + count + " times");
}
}
using System;
public class Exercise34
{
public static void Main()
{
int[] a = { 3,4,5,6,7,8,3,4,5,6,7,8,9,9};
int n = a.Length-1;
int dupcounter = 0;
for (int i = 0; i < n; i++)
{
int counter = 0;
for (int j = i + 1; j <= n; j++)
{
if (a[i] == a[j])
{
counter++;
n--;
if (counter == 1)
{
dupcounter++;
Console.WriteLine(a[i]);
}
for (int k = j; k <= n; k++)
{
a[k] = a[k + 1];
}
}
}
}
Console.WriteLine(dupcounter);
}
}
For String I print all the duplicates and their counts. Please check above code and my logic.
package Interview_Strings;
import java.util.Arrays;
public class print_duplicates_and_their_counts
{
static void printDupCount(String str)
{
char[] charString=str.toCharArray();
Arrays.sort(charString);
int size=charString.length;
int j=1,i=0;
int count=0;
while(i<size && j<size)
{
if(charString[i]!=charString[j])
{
count=j-i;
System.out.println(charString[i]+" : "+count);
i=j;
j++;
if(j>=size)
{
System.out.println(charString[j-1]+" : "+count);
}
}
else
{
j++;
}
}
}
public static void main(String args[])
{
String str="bigbangtheory";
printDupCount(str);
}
}
output:
a : 1
b : 2
e : 1
g : 2
h : 1
i : 1
n : 1
o : 1
r : 1

Sorting an Array in Java, then printing it

I have an error in my code, since it is not printing all of the elements of the array after it's been sorted. Can someone spot it and help me out? (I am only in my 5th week of Java, so definitely a newbie!)
public class Test01 {
public static void main(String[] args) {
int[] arr = {1, 3, 5, 4, 2};
for (int i = 0; i < arr.length - 1; i++) {
int currentMin = arr[i];
int currentMinIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (currentMin > arr[j]){
currentMin = arr[j];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
arr[currentMinIndex] = arr[i];
arr[i] = currentMin;
}
System.out.print(arr[i] + " ");
}
}
}
The current output for this is:
1 2 3 4
So I am just missing printing the '5'
thanks for the help!
You are running the loop an index short. Change
for (int i = 0; i < arr.length - 1; i++) { // The -1 is the issue
to
for (int i = 0; i < arr.length ; i++) {
public class Test01 {
public static void main(String[] args) {
int[] arr = {1, 3, 5, 4, 2};
for (int i = 0; i < arr.length; i++) {
int currentMin = arr[i];
int currentMinIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (currentMin > arr[j]){
currentMin = arr[j];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
arr[currentMinIndex] = arr[i];
arr[i] = currentMin;
}
System.out.print(arr[i] + " ");
}
}
}

Categories

Resources