I want to print numbers in a 2d array in ascending order without the use of any sorting technique. Here is my code:
public class ArraySort2D
{
public static void main(String s)
{
int[][] arr={ {4,3,2,7,1}, {7,5,4,6,3}};
for(int k=0; k<=1; k++)
{
for(int i=0; i<arr.length; i++)
{
for(int j=1; j<arr.length-i; j++)
{
if(arr[k][j-1]>arr[k][j])
{
int dummy=arr[k][j-1];
arr[k][j-1]=arr[k][j];
arr[k][j]=dummy;
}
}
}
}
for(int p=0; p<arr.length; p++)
{
for(int g=0; g<arr[p].length; g++)
{
System.out.println(arr[p][g]);
}
}
}
}
I want the output as:
1 2 3 4 7 3 4 5 6 7
I am using a dumb sorting algorithm but you should be able to easily adapt whatever sorting algorithm you want to the sorting method i use
public static void main(String[] args) {
int[][] arr= { {4,3,2,7,1},
{7,5,4,6,3}
};
for(int index = 0; index < arr.length; index++)
sortArray(arr[index]);
printArray(arr);
}//main method
public static int[] sortArray(int[] ogArray)
{
for(int i = 0; i < ogArray.length; i++)
{
if(i + 1 < ogArray.length && ogArray[i] > ogArray[i + 1])
{
int temp = ogArray[i + 1];
ogArray[i + 1] = ogArray[i];
ogArray[i] = temp;
i = -1;
}
}
return ogArray;
}
public static void printArray(int[][] temp)
{
for(int i = 0; i < temp.length; i++)
{
for(int j = 0; j < temp[i].length; j++)
{
System.out.print(temp[i][j]);
}
}
}
Output is
1234734567
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.