JAVA implements array sorting (program exercise)

method 1:

package fun;
//方法1:冒泡排序
public class BubbleSort {
	public static void main(String[] args) {
		int score[]={88,55,99,35,51,6,92};
		//int score[]={1,2,3,4,5,6,7};
		for(int i=0;i<score.length;i++){
			for(int j=0;j<score.length-1-i;j++){
				if(score[j]<score[j+1]){
					int temp=score[j];
					score[j]=score[j+1];
					score[j+1]=temp;
				}
			}
			System.out.println("第"+(i+1)+"次排序结果:");
			for(int a=0;a<score.length;a++){
				System.out.println(score[a]+"\t");
			}
			System.out.println("");
		}
		System.out.println("最终排序结果:");
		for(int a=0;a<score.length;a++){
			System.out.println(score[a]+"\t");
		}
	}
}

operation result:

1st sorting result:
88 
99 
55 
51 
35 
92 

2nd sorting result:
99 
88 
55 
51 
92 
35 

3rd sorting result:
99 
88 
55 
92 
51 
35 

4th sorting result:
99 
88 
92 
55 
51 
35 

5th sort result:
99 
92 
88 
55 
51 
35 

6th sort result:
99 
92 
88 
55 
51 
35 

7th sort result:
99 
92 
88 
55 
51 
35 

Final sort result:
99 
92 
88 
55 
51 
35 

illustrate: 

Each loop takes the jth element and compares it with the j+1 element, and puts the smaller one at the back.

E.g:

in the first loop

First take the first element and compare it with the second element, 88 is greater than 55, then the array becomes 88, 55, 99, 35, 51, 6, 92

Then take the second element and compare it with the third element, 99 is greater than 55, then the array becomes 88, 99, 55, 35, 51, 6, 92

Then take the third element and compare it with the fourth element, 55 is greater than 35, then the array becomes 88, 99, 55, 35, 51, 6, 92

Then take the 4th element and compare it with the 5th element, 51 is greater than 35, then the array becomes 88, 99, 55, 51, 35, 6, 92

Then take the 5th element and compare it with the 6th element, 35 is greater than 6, then the array becomes 88, 99, 55, 51, 35, 6, 92

Then take the 6th element and compare it with the 7th element, 92 is greater than 6, then the array becomes 88, 99, 55, 51, 35, 92, 6

At this point the first cycle ends. Output array: 88,99,55,51,35,92,6

ps: I originally wanted to practice writing a few sorting methods, then test the running time of each method, and compare the pros and cons of each method. It turned out that there are already many similar content on the Internet. attached below

Sorting Algorithm:

https://blog.csdn.net/coolwriter/article/details/78732728

http://www.cnblogs.com/0201zcr/p/4763806.html

Binary tree:

https://www.cnblogs.com/Java3y/p/8636522.html

Heap sort:

https://www.cnblogs.com/Java3y/p/8639937.html

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324129403&siteId=291194637