The principle of bubble sorting: his basic principle is to compare the values of the adjacent elements (in particular, and the group comparison), if the conditions are met to exchange element values, the smaller elements and the larger elements of exchange, so that small elements like small bubbles from the bottom up to the top, large elements like large bubbles from the top of the sink to the end.
1. Suitable crowd: Students with a certain Java SE Foundation, understand the Java data type, array definition, initialization and common array methods, as well as the Java loop operation.
2. Preparation: Preferably a development tool such as: Eclipse or MyEclipse can, of course, you use a DOS system to compile and run all can, just change the bug will be a bit troublesome.
3. Algorithm implementation:
public class bubblesort{
public static void Main (string[] args) {
First, create an unordered array.
Int[] Array = {100,120,530,1,2,48,26};//int[] array and int array[] are OK, but the former is recommended
Create an object for the bubbling Sort class
Bubblesort arraysort = new Bubblesort ();
Call sort method to sort an array
Arraysort.sort (array);
}
public void sort (int[] array) {
for (int i= 1;i<array.length;i++)
{
Start comparing values of neighboring elements, sinking large elements
for (int j=0;j<array.length-i;j++) {
if (Array[j]>array[j+1]) {
Exchange values for two elements if conditions are met
int temp = Array[j];
ARRAY[J]=ARRAY[J+1];
Array[j+1]=temp;
}
}
}
Showarray (array);
}
Show all elements in an array
public void Showarray (int[] array) {
An uncommon foreach loop used here, not accustomed to this notation can be used for loop
/*
for (int i=0;i<array.length;i++)
{
System.out.print (array[i]+ "");
}
*/
for (int i:array)
{
System.out.print (i+ "");
}
}
}
4. Advantages and disadvantages of bubble sorting:
Advantages: Relatively simple, space complexity is low, is stable. Advantages:
Disadvantage: The time complexity is too high, the efficiency is not good.
5. PostScript: Bubble sorting is the first class of sorting algorithm, is also the most easy to start a sorting algorithm, follow-up I will introduce you more practical but more complex sorting algorithm
Java Bubble sort