정렬(1) 단순 정렬

2177 단어 정렬
거품 정렬
	public static int[] data = {3,7,8,0,9,5,4,1,6,2};
	
	public static void main(String[] args) {
		int len = data.length;
		System.out.println(Arrays.toString(data));
		for(int i = 0; i < len - 1; i++){
			for(int j = i + 1; j < len; j++){
				if(data[i] > data[j]){
					swap(i, j);
				}
			}
			System.out.println();
			System.out.println(Arrays.toString(data));
		}

	}
	private static void swap(int index1, int index2){
		int temp = data[index1];
		data[index1] = data[index2];
		data[index2] = temp;
		System.out.print("[" + data[index1] + ":" + data[index2] + "]");
	}

 
정렬 선택
	public static int[] data = {3,7,8,0,9,5,4,1,6,2};
	
	public static void main(String[] args) {
		int len = data.length;
		System.out.println(Arrays.toString(data));
		System.out.println();
		for(int i = 0; i < len - 1; i++){
			int min = i;
			for(int j = i + 1; j < len; j++){
				if(data[min] > data[j]){
					min = j;
				}
			}
			swap(i, min);
			System.out.println(Arrays.toString(data));
		}
	}
	private static void swap(int index1, int index2){
		int temp = data[index1];
		data[index1] = data[index2];
		data[index2] = temp;
		System.out.println("[" + data[index1] + ":" + data[index2] + "]");
	}

삽입 정렬
	public static int[] data = {3,7,8,0,9,5,4,1,6,2};
	
	public static void main(String[] args) {
		int len = data.length;
		System.out.println(Arrays.toString(data));
		System.out.println();
		for(int i = 1; i < len; i++){
			System.out.println("i =" + i);
			int temp = data[i];
			int j = i - 1;
			while(j >= 0 && data[j] >= temp){
				data[j + 1] = data[j];
				j--;
			}
			data[j + 1] = temp;
			System.out.println(Arrays.toString(data));
		}
	}

  

좋은 웹페이지 즐겨찾기