* 버블 소트

* O(N^2)

*클래스
package algo.bubble;

public class MyBubbleSort {

	public void sort(Integer[] array) {

		for(int i = 0 ; i < array.length ; i++)
			System.out.print(array[i] + " ");
		System.out.print(" -->  ");
		

		int temp = 0;
		
		for (int i = 0 ; i < array.length - 1 ; i++) {

			for (int j = 0 ; j < array.length - 1 - i; j++) {

				if(array[j] > array[j + 1]) {
				
					temp = array[j];
					array[j] = array[j + 1];
					array[j + 1] = temp;
					
				}
				
			}

		}

		for(int i = 0 ; i < array.length ; i++)
			System.out.print(array[i] + " ");
		System.out.println();

	}

}

*테스트
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import algo.bubble.MyBubbleSort;

public class Main {

	public static void main(String[] args) {

		MyBubbleSort sort = new MyBubbleSort();
		for(int i = 0 ; i < 10 ; i ++)
			sort.sort(getRandArr());

	}

	public static Integer[] getRandArr() {

		List<Integer> arr = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
		Collections.shuffle(arr);
		Collections.shuffle(arr);
		return (Integer[])arr.toArray();
		
	}

}

<결과>
1 10 3 5 8 4 2 7 9 6  -->  1 2 3 4 5 6 7 8 9 10 
2 8 1 10 9 7 4 6 3 5  -->  1 2 3 4 5 6 7 8 9 10 
7 2 5 1 3 4 6 8 9 10  -->  1 2 3 4 5 6 7 8 9 10 
7 8 10 3 2 9 4 1 5 6  -->  1 2 3 4 5 6 7 8 9 10 
7 8 1 4 10 5 3 6 9 2  -->  1 2 3 4 5 6 7 8 9 10 
2 8 5 9 10 6 7 3 4 1  -->  1 2 3 4 5 6 7 8 9 10 
3 9 8 7 10 1 5 6 4 2  -->  1 2 3 4 5 6 7 8 9 10 
10 6 4 2 9 7 1 8 3 5  -->  1 2 3 4 5 6 7 8 9 10 
5 7 9 10 1 6 2 8 4 3  -->  1 2 3 4 5 6 7 8 9 10 
10 8 1 9 6 5 3 7 4 2  -->  1 2 3 4 5 6 7 8 9 10 


'Algorithm - Using java' 카테고리의 다른 글

Heap Sort  (0) 2018.05.28
Randomized Quick Sort  (0) 2018.05.27
Merge Sort  (0) 2018.05.27
Insertion Sort  (0) 2018.05.27
Selection Sort  (0) 2018.05.27

+ Recent posts