在Core java中按升序对数组元素进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20945237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:28:38 来源:igfitidea点击:
sort array element in a ascending order in Core java?
提问by tstk
class Ascendingarray {
public static void main(String[] args) { //Without using Arrays.sort function
int i; int nos[] = {12,9,-4,-1,3,10,34,12,11};
System.out.print("Values before sorting: \n");
for(i = 0; i < nos.length; i++)
System.out.println( nos[i]+" ");
//sort(nos, nos.length);
System.out.print("Values after sorting: \n");
for(i = 0; i
回答by kai
You can sort it by your own with a sorting method like bubblesort. Use nested for loops.
您可以使用诸如冒泡排序之类的排序方法自行对其进行排序。使用嵌套的 for 循环。
for (int j = 0; j<array.length; j++) {
for (int k = 0; k < array.length; k++){
if (array[j] < array[k]) {
int buffer = array[j];
array[j] = array[k];
array[k] = buffer;
}
}
}
回答by SSH
Here is the code for sorting
这是排序的代码
for (int j = 0; j<array.length-1; j++) {
for (int k = j+1; k < array.length; k++){
if (array[j] < array[k]) {
int dummy = array[j];
array[j] = array[k];
array[k] = dummy;
}
}
}