I need to make 2 arrays and sort one into the other in ascending order and display it. I've managed to move ar[] into sorted[], but I can't get it to actually sort.
Here's what I have so far:
public class SortArray
{
public static void main(String argv[])
{
int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
int sorted[] = new int[7];
for (int i=0; i<ar.length-1; i++)
{
int smallest = 1000000;
int index = 0;
for (int j=i+1; j<sorted.length; j++)
{
if (ar[i] < smallest)
{
smallest=i;
int tmp = ar[i];
ar[i] = sorted[j];
sorted[j] = tmp;
}
}
}
for(int i=0; i<sorted.length; i++)
{
System.out.println("sorted[" + i + "] = " + sorted[i]);
}
}
}
Just try to understand and use java algorithms here. If you have problems with understanding the idea please do not hesitate to ask.
http://www.java2novice.com/java-sorting-algorithms/
They are more efficient and they are not error prone.
Assuming that you are trying to learn sorting algorithms and coding, here is what you are trying to; Please be aware that if there are identical values it will get only one of them.
int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
int sorted[] = new int[6];
int smallestFound=-1;
for (int i=0; i<ar.length-1; i++)
{
int smallest = 1000000;
for (int j=0; j<sorted.length; j++)
{
if (ar[j] < smallest && ar[j]>smallestFound) {
smallest = ar[j];
}
}
smallestFound=smallest;
sorted[i] = smallest;
}
for(int i=0; i<sorted.length; i++)
{
System.out.println("sorted[" + i + "] = " + sorted[i]);
}
you can use a TreeSet , it sort the element naturally:
public class SortArray
{
public static void main(String argv[])
{
int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
int sorted[] = new int[7];
List<Integer> sortedList = new TreeSet<Integer>();
for (int i=0; i<ar.length-1; i++) {
sortedList.add(ar[i]);
}
// transform into array
for(int i = 0; i< sortedList.size(); i++) {
sorted[i] = sortedList.get(i)
}
for(int i=0; i<sorted.length; i++)
{
System.out.println("sorted[" + i + "] = " + sorted[i]);
}
}
}
Related
How can I reverse rows in a matrix, which sums less than the sum last column?
For example:
1,2,3 -> sumRow1 = 6;
4,5,6 -> sumRow2 = 15;
7,8,9 -> sumRow3 = 24;
sumLastCol = 18;
row1 & row2 - reverse, row3 - unchange
Can I do it at once in the matrix or do I need to create a new array?
This is my code, but it doesn't work correctly:
public static void reverseMatrix(int n, int[][]randMatrix, int sumRow, int sumCol){
for(int i=0; i<n; i++){
int start = 0;
int end = n-1;
if(sumRow<sumCol) {
while (start < end) {
int temp = randMatrix[i][start];
randMatrix[i][start] = randMatrix[i][end];
randMatrix[i][end] = temp;
start++;
end--;
}
}
}
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
System.out.print(randMatrix[i][j]+"\t");
}
System.out.println();
}
}
public static int sumLastColumn(int n, int[][]randMatrix){
int sumCol = 0;
for(int i=0; i<n; i++){
int[]row = randMatrix[i];
sumCol += row[row.length-1];
}
System.out.println("SumLastCol: "+sumCol);
return sumCol;
}
public static int sumRows(int n, int[][]randMatrix) {
int sumRow = 0;
for (int i=0; i<n; i++) {
sumRow = 0;
for (int j=0; j<n; j++) {
sumRow = sumRow + randMatrix[i][j];
}
System.out.println("SumRow"+(i+1)+": " + sumRow);
}
return sumRow;
}
}
If you know how to do it, please help me:)
Here's an easy way.
int[][] mat = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
First, compute the sum of the last column.
stream each row
map the last value in the row
and sum them.
int lastColSum = Arrays.stream(mat).mapToInt(s->s[s.length-1]).sum();
Now just iterate across the rows, summing them and comparing to the lastColSum and reverse if required.
for (int[] row :mat) {
if (Arrays.stream(row).sum() < lastColSum) {
reverse(row);
}
}
for (int[] row :mat) {
System.out.println(Arrays.toString(row));
}
prints
[3, 2, 1]
[6, 5, 4]
[7, 8, 9]
Helper method to reverse the row. It works by swapping values at it moves outside toward the middle. This works for even or odd length rows.
public static void reverse(int [] v) {
for(int i = 0; i < v.length/2; i++) {
int t = v[0];
v[0] = v[v.length-i-1];
v[v.length-i-1] = t;
}
}
By using following I am able to find most frequently occurring integer in an array. But following code it will not work for few scenarios. How can I fix the code inside for loop? I want to enhance this approach only.
class FindingMostFrequencyOccur {
public static void main(String args[]) {
int A[] = { 1, 2, 3, 3, 1, 3, 1};
int M = 3; // Maximum Number in Array
int result = findFrequency(M, A);
System.out.println("Result "+result);
}
static int findFrequency(int M, int[] A) {
int N = A.length;
int[] count = new int[M + 1];
for (int i = 0; i <= M; i++)
count[i] = 0;
int maxOccurence = 1;
int index = -1;
for (int i = 0; i < N; i++) {
if (count[A[i]] > 0) {
int tmp = count[A[i]];
if (tmp > maxOccurence) {
maxOccurence = tmp;
index = i;
}
count[A[i]] = tmp + 1;
} else {
count[A[i]] = 1;
}
}
return A[index];
}
}
Can you we improve in this line
if (count[A[i]] > 0) {
int tmp = count[A[i]];
if (tmp > maxOccurence) {
maxOccurence = tmp;
index = i;
}
count[A[i]] = tmp + 1;
} else {
count[A[i]] = 1;
}
To get the frequency of m in a use:
static int findFrequency(int m, int[] a) {
return (int)IntStream.of(a).filter(i-> i==m).count();
}
To get a map of all frequencies in a use:
static Map<Integer, Integer> findFrequency(int[] a) {
Map<Integer, Integer> m = new HashMap<>();
IntStream.of(a).distinct().forEach(i->{
m.put(i, findFrequency(i,a));
});
return m;
}
In this logic, you take each element of the array, and find the number of times it is repeated to the right of it, in the array. This is given by local_frequency. If this happens to be more than max_frequency, then this number at arr[i] is stored in number, and then max_frequency stores local_frequency
public static void main(String[] args)
{
int[] arr = {1, 2, 3, 4, 3, 2, 1, 5, 5, 5, 4, 4, 3, 4};
int result = findMostFrequent(arr);
System.out.println(result + " is the most frequent number");
}
public static int findMostFrequent(int[] arr)
{
int number = arr[0];
int maxFrequency = 0;
for(int i =0 ; i < arr.length; i++)
{
int local_frequency = 0;
for(int j = i; j < arr.length; j++)
{
if(arr[i] == arr[j])
local_frequency++;
}
if(local_frequency > maxFrequency)
{
number = arr[i];
maxFrequency = local_frequency;
}
}
return number;
}
public class DiagonalSort {
static int sortDiagonal(int m[][]) {
int[] intArray = new int[4];
int k=0;
//to insert 2d array diagonal elements into 1d array
for(int i = 0; i<m.length; i++){
for(int j= 0; j<m[i].length; j++) {
if(i == j) {
int n = m[i][j];
intArray[k]=n;
k++;
}
}
}
// sorting 1d array elements
Arrays.sort(intArray);
// inserting sorted elements to its appropriate positions
for(int i = 0; i<m.length; i++){
for(int j= 0; j<m[i].length; j++) {
if(i == j) {
m[i][j]= intArray[i];
}
}
}
//printing the diagonal elements
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}
return 0;
}
public static void main(String args[])
{
int m[][] = { { 36, 10, 24, 8 },
{ 12, 23, 0, 2 },
{ 9, 5, 10, 2 },
{ 6, 3, 1, 2 } };
sortDiagonal(m);
} }
I have used very simple logic:
first insert the diagonal elements to 1d array
sort the 1d array
insert the elements of sorted 1d array into 2d array diagonal positions
Always welcome for more efficient answer.
1.Your logic is good enough but you can optimize your code by removing some extra loops.
2.If you want to access only diagonal elements then you don't need to run 2 loops.
3.You can do like this
package test.code;
import java.util.Arrays;
public class DiagonalSort {
static int sortDiagonal(int m[][]) {
int[] intArray = new int[4];
//to insert 2d array diagonal elements into 1d array
for(int i = 0; i<m.length; i++){
intArray[i] = m[i][i];
}
// sorting 1d array elements
Arrays.sort(intArray);
// inserting sorted elements to its appropriate positions
for(int i = 0; i<m.length; i++){
m[i][i]= intArray[i];
}
//printing the diagonal elements
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}
return 0;
}
public static void main(String args[])
{
int m[][] = { { 36, 10, 24, 8 },
{ 12, 23, 0, 2 },
{ 9, 5, 10, 2 },
{ 6, 3, 1, 2 } };
sortDiagonal(m);
} }
**Java class to sort diagonal element**
class Solution {
public int[][] diagonalSort(int[][] mat) {
int row=mat.length;
int col=mat[0].length;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
for(int r=i+1,c=j+1;r<row && c<col;r++,c++){
if(mat[i][j]>mat[r][c]){
// Swap the value
int temp=mat[i][j];
mat[i][j]=mat[r][c];
mat[r][c]=temp;
}
}
}
}
return mat;
}
}
I need to use recursion that takes in array of integers and has the even integers appear before the odd integers i.e an array of [1,2,3,4,5] should look like [2,4,1,3,5]. Please note that the integers do not need to be in any specific order just even before odd. Here is what I have so far, any help would be appreciated!
public class EBOMain {
static int[] Array = { 1, 2, 3, 4, 5, 6};
static int n;
public static void main(String[] args) {
System.out.print("Array before sort: " );
for (int i = 0; i < Array.length; i++)
System.out.print(Array[i] +" ");
n = Array.length;
rearrange(Array, n);
System.out.print("\nArray after sort: " );
for (int i = 0; i < Array.length; i++)
System.out.print(Array[i] +" ");
}
public static void rearrange(int []Array,int n){
if (n==0)
return;
else if(Array[n-1]%2==0) {
for(int i=0;i<n-1;i++) {
if(Array[i]%2!=0) {
int temp = Array[i];
Array[i]= Array[n-1];
Array[n-1] = temp;
rearrange(Array,n-1);
}
}
}
else
rearrange(Array,n-1);
}
}
You forgot to initialize n with the length of the array in the first call to rearrange. See this corrected code. Make sure you use Java code conventions; I renamed the Arrayvariable to array.
public class EBOMain {
static int[] array = { 1, 2, 3, 4, 5, 6 };
public static void main(String[] args) {
System.out.print("array before sort: ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
rearrange(array, array.length); // <-- Change is here
System.out.print("\narray after sort: ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
public static void rearrange(int[] array, int n) {
if (n == 0) {
return;
} else if (array[n - 1] % 2 == 0) {
for (int i = 0; i < n - 1; i++) {
if (array[i] % 2 != 0) {
int temp = array[i];
array[i] = array[n - 1];
array[n - 1] = temp;
rearrange(array, n - 1);
}
}
} else {
rearrange(array, n - 1);
}
}
}
Output:
array before sort: 1 2 3 4 5 6
array after sort: 6 2 4 1 3 5
import java.util.*;
import java.util.Random;
class ArraySorting {
public static void main(String[]args) {
ArrayList<Integer> arr = new ArrayList<Integer>();
Random generate = new Random();
for (int nums = 0; nums < 20; nums++) {
int randomnumbers = generate.nextInt(50);
arr.add(randomnumbers);
}
System.out.println("First list of 20 generated numbers: ");
System.out.println(arr);
System.out.println("");
int dupe = 0;
for (int n = 0; n < arr.size(); n++) {
Integer check1 = arr.get(n);
for (int n2 = n+1; n2 < arr.size(); n2++) {
Integer check2 = arr.get(n2);
//remove second num if two numbers akike
if (check1.equals(check2)) {
arr.remove(check2);
n2 = n2-1;
dupe = 1;
}
}
n = n-dupe;
dupe = 0;
}
System.out.println("Duplicates: " + (20 - arr.size()));
for (int n3 = arr.size(); n3 < 20; ++n3) {
int randomnumbers = generate.nextInt(50);
arr.add(randomnumbers);
//check for duplicates again
for (int n = 0; n < arr.size(); n++) {
Integer check1 = arr.get(n);
for (int n2 = n+1; n2 < arr.size(); n2++) {
Integer check2 = arr.get(n2);
if (check1.equals(check2)) {
arr.remove(check2);
n2 = n2-1;
dupe = 1;
}
}
n = n - dupe;
dupe = 0;
}
}
//before sort
System.out.println(arr);
System.out.println("");
for(int a=0; a<20; a++){
for (int b = 0; b < 19; b++) {
if(arr[b] > arr[b+1]){
int temporary = arr[b];
arr[b] = arr[b+1];
arr[b+1] = temporary;
}
}
}
System.out.println("\nSorted Array:\n");
for (int a = 0; a < 20; a++) {
System.out.println("Array [" + a + "]: " + arr[a]);
}
}
}
Can anyone tell me what I did wrong for this one, I can't seem to generate the last part. Shouldn't the ArrayList arr = new ArrayList(); run same with the last part where arr[b] is work? I'm new to Java so would greatly appreciate if simple explaination/metaphor is ued provided with solution.
P.S: I'm not planning to use a library sort function like Collection, I'm required to use the sorting method at the last part.
arr[a] is the syntax to access array elements. For ArrayLists you use arr.get(a). And to assign a value to an ArrayList, you use arr.set(b,value). You can't use the assignment operator.
The problem you are having is that you are trying to remove your duplicates before sorting. First, sort your integers, duplicates and all, and then remove the duplicates.
import java.util.ArrayList;
import java.util.Random;
public class ArraySorting {
public static void main(String[]args) {
ArrayList<Integer> arr = new ArrayList<Integer>();
Random generate = new Random();
for (int nums = 0; nums < 20; nums++) {
int randomnumbers = generate.nextInt(10);
arr.add(randomnumbers);
}
System.out.println("First list of 20 generated numbers: ");
System.out.println(arr);
System.out.println("");
// SORT YOUR LIST FIRST
bubbleSort(arr);
System.out.println(arr);
// NOW YOU CAN REMOVE YOUR DUPLICATES
removeDuplicates(arr);
System.out.println(arr);
}
public static void bubbleSort(ArrayList<Integer> list){
for(int i = 0; i < list.size(); i++) {
for(int j = 1; j < (list.size() -i); j++) {
if(list.get(j - 1) > list.get(j)) {
int temp = list.get(j-1);
list.set(j-1, list.get(j));
list.set(j, temp);
}
}
}
}
public static void removeDuplicates(ArrayList<Integer> list){
for(int i = 0; i < list.size(); i++) {
if(i < list.size()-1) {
int prev = list.get(i);
int curr = list.get(i + 1);
if(curr == prev) {
list.remove(list.get(i + 1));
i--;
}
}
}
}
}
Output
First list of 20 generated numbers:
[9, 2, 2, 1, 3, 4, 0, 9, 5, 2, 5, 7, 4, 9, 0, 4, 0, 6, 6, 6]
[0, 0, 0, 1, 2, 2, 2, 3, 4, 4, 4, 5, 5, 6, 6, 6, 7, 9, 9, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 9]