java排序链表冒泡排序
Java Sorting is one of the many aspects of java interview questions. In this post, we will see java bubble sort example and write a program for bubble sort.
Java排序是Java面试问题的众多方面之一。 在这篇文章中,我们将看到Java冒泡排序示例并编写一个冒泡排序程序。
Bubble sort is also known as the exchange sort. It is the simplest algorithm for sorting numbers.
冒泡排序也称为交换排序。 这是最简单的数字排序算法。
Here is the implementation of Bubble Sort in Java program.
这是Java程序中的冒泡排序的实现。
import java.util.Arrays;
public class BubbleSort {
public static void main(String args[]) {
int arr[] = { 5,4,3,2,1 };
int arr1[] = { 1,2,3,4,5 };
System.out.println("Array after sorting in ascending order:"+Arrays.toString(bubbleSortAscending(arr)));
System.out.println("Array after sorting in descending order:"+Arrays.toString(bubbleSortDescending(arr1)));
}
public static int[] bubbleSortAscending(int[] arr){
int temp;
for(int i=0; i < arr.length-1; i++){
for(int j=1; j < arr.length-i; j++){
if(arr[j-1] > arr[j]){
temp=arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
//check that last index has highest value in first loop,
// second last index has second last highest value and so on
System.out.println("Array after "+(i+1)+"th iteration:"+Arrays.toString(arr));
}
return arr;
}
public static int[] bubbleSortDescending(int[] arr){
int temp;
for(int i=0; i < arr.length-1; i++){
for(int j=1; j < arr.length-i; j++){
if(arr[j-1] < arr[j]){
temp=arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
//check that last index has highest value in first loop,
// second last index has second last highest value and so on
System.out.println("Array after "+(i+1)+"th iteration:"+Arrays.toString(arr));
}
return arr;
}
}
The above program is for sorting in ascending as well as descending order using bubble sort algorithm.
上面的程序用于使用冒泡排序算法按升序和降序进行排序。
Output of the above program is:
上面程序的输出是:
Array after 1th iteration:[4, 3, 2, 1, 5]
Array after 2th iteration:[3, 2, 1, 4, 5]
Array after 3th iteration:[2, 1, 3, 4, 5]
Array after 4th iteration:[1, 2, 3, 4, 5]
Array after sorting in ascending order:[1, 2, 3, 4, 5]
Array after 1th iteration:[2, 3, 4, 5, 1]
Array after 2th iteration:[3, 4, 5, 2, 1]
Array after 3th iteration:[4, 5, 3, 2, 1]
Array after 4th iteration:[5, 4, 3, 2, 1]
Array after sorting in descending order:[5, 4, 3, 2, 1]
As we can see that in every iteration, the last index is getting sorted and it takes (array length – 1) iterations for sorting.
正如我们看到的那样,在每个迭代中,最后一个索引将被排序,并且需要(数组长度– 1)次迭代才能进行排序。
翻译自: https://www.journaldev.com/557/bubble-sort-java
java排序链表冒泡排序