Sorting - Bubble Sort [Easy]
https://ithelp.ithome.com.tw/articles/10226353
Sample Input 0
STDIN Function
----- --------
3 a[] size n = 3
1 2 3 a = [1, 2, 3]
Sample Output 0
Array is sorted in 0 swaps.
First Element: 1
Last Element: 3
Explanation 0
The array is already sorted, so swaps take place.
Sample Input 1
3
3 2 1
Sample Output 1
Array is sorted in 3 swaps.
First Element: 1
Last Element: 3
Explanation 1
The array is not sorted, and its initial values are: . The following swaps take place:
At this point the array is sorted and the three lines of output are printed to stdout.
static void countSwaps(int[] a) {
int temp;
int totalswap=0;
for(int i=0;i<a.length;i++)
{
for (int j=0;j<a.length-1;j++)
{
int swap=0;
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
swap++;
}
totalswap += swap;
}
}
System.out.println("Array is sorted in "+totalswap+" swaps.");
System.out.println("First Element: "+a[0]);
System.out.println("Last Element: "+a[a.length-1]);
}
留言
張貼留言