![](/img/trans.png)
[英]How to sort a 2 dimensional array with all elements in ascending order in java
[英]Sort elements of an array in ascending order
我正在嘗試按升序對數組進行排序。 由於某種原因,它僅執行一次for循環。 為什么直到一切都整理好之后它才繼續前進?
它用於分配作業,因此不允許使用現有的排序方法。 我應該自己寫方法。
public class Sudoku {
public static void main(String[] args) {
int[] a = { 1, 4, 3, 5, 2 };
System.out.println(Arrays.toString(sortArray(a)));
}
public static int[] sortArray(int[] nonSortedArray) {
int[] sortedArray = new int[nonSortedArray.length];
int temp;
for (int i = 0; i < nonSortedArray.length - 1; i++) {
if (nonSortedArray[i] > nonSortedArray[i + 1]) {
temp = nonSortedArray[i];
nonSortedArray[i] = nonSortedArray[i + 1];
nonSortedArray[i + 1] = temp;
sortedArray = nonSortedArray;
}
}
return sortedArray;
}
}
public static int[] sortArray(int[] nonSortedArray) {
int[] sortedArray = new int[nonSortedArray.length];
int temp;
for (int j = 0; j < nonSortedArray.length - 1; j++) {// added this for loop, think about logic why do we have to add this to make it work
for (int i = 0; i < nonSortedArray.length - 1; i++) {
if (nonSortedArray[i] > nonSortedArray[i + 1]) {
temp = nonSortedArray[i];
nonSortedArray[i] = nonSortedArray[i + 1];
nonSortedArray[i + 1] = temp;
sortedArray = nonSortedArray;
}
}
}
return sortedArray;
}
輸出: [1、2、3、4、5]
要么
//making use of j
public static int[] sortArray(int[] nonSortedArray){
int[] sortedArray = new int[nonSortedArray.length];
int temp;
for (int i = 0; i <= nonSortedArray.length; i++)
{
for (int j = i+1; j < nonSortedArray.length; j++)
{
if (nonSortedArray[i] > nonSortedArray[j])
{
temp = nonSortedArray[i];
nonSortedArray[i] = nonSortedArray[j];
nonSortedArray[j] = temp;
sortedArray = nonSortedArray;
}
}
}
return sortedArray;
}
arr = new int[Item];
Arrays.sort(arr);
Java中的內置函數可按升序對數組進行排序。
您正在嘗試使用單個循環對數組進行排序。 您將需要兩個循環來確保元素按排序順序。
public static int[] sortArray(int[] nonSortedArray)
{
int[] sortedArray = new int[nonSortedArray.length];
int temp;
for (int i = 0; i < nonSortedArray.length-1; i++)
{
for (int j = i+1; j < nonSortedArray.length; j++)
{
if (nonSortedArray[i] > nonSortedArray[j])
{
temp = nonSortedArray[i];
nonSortedArray[i] = nonSortedArray[j];
nonSortedArray[j] = temp;
sortedArray = nonSortedArray;
}
}
}
return sortedArray;
}
這將以升序對數組進行排序
int arr[]={33,3,4,5,1};
Arrays.sort(arr);
System.out.println(Arrays.toString (arr));
輸出將為:-[1、3、4、5、33]
升序排列數組
private static int[] sort(int[] array) {
int[] new_array = new int[array.length];
int count=0;
for (int i=0; i<array.length; i++) {
for(int j=i+1; j<array.length+i;j++) {
if(array[i]>=array[j%array.length])
count++;
}
for(int loc=count; loc>0;loc--) {
if(new_array[loc]==0)
{
new_array[loc]=array[i];
break;
}
}
count=0;
}
return new_array;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.