Bubble sort and selection ordering for "Java" arrays (principle + code implementation) __java

Source: Internet
Author: User

first, bubble sort



Code implementation:

public class Test_bubblesort {public
	static void Main (string[] args) {
		int[] arr = {23,56,15,13,36};
		Bubblesort (arr);
		Print (arr);		
	}
	Bubble sort public
	static void Bubblesort (int[] arr) {for
		(int i = 0;i <arr.length-1; i++) {for
			(int j = 0; J &L T Arr.length-1-i; J + +) {
				if (Arr[j] > Arr[j+1]) {
				int temp = arr[j];
				ARR[J] = arr[j+1];
				ARR[J+1] = temp; 
				Swap (arr,i,j+1);
	}}}} Print
	private static void print (int[] arr) {for
		(int i = 0;i < arr.length;i++) {
			System.out.println (arr[ I]);
		}
	
	Convert public
	static void Swap (int[] Arr,int i,int j) {
		int temp = arr[i];
		Arr[i] = arr[j];
		ARR[J] = temp;	
	}
}

The time complexity of the algorithm is O (n^2), and the space complexity is O (1).

Second, select the sort


Code implementation:

public class test_selectsort{public
	static void Main (string[] args) {			
			int[] arr = {4,7,2,9,0,5};
			Selectsort (arr);
			Print (arr);		
		}
	Select sort public
	static void Selectsort (int[] arr) {for
		(int i = 0; i < arr.length-1; i++) {for
			(int j = i+1; J < Arr.length; J + +) {			
				if (Arr[i] > Arr[j]) {
				    int temp = arr[i];
				    Arr[i] = arr[j];
				    ARR[J] = temp;		
				    Swap (ARR,I,J);
	}}}} Print public
	static void print (int[] arr) {for
		(int k =0;k<arr.length;k++)
		{
		      System.out.println (Arr[k]);
		}
	
	Transposition operation
	private static void Swap (int[] Arr,int i,int j) {
		int temp = arr[i];
		Arr[i] = arr[j];
		ARR[J] = temp;	
	}
}
The time complexity of the algorithm is O (n^2), and the space complexity is O (1).
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.