BACKEND/Java

[Java] 알고리즘 - 정렬 예제

Hello? 2017. 10. 20. 16:59

● 선택 정렬


public class SelectionSort {

public static void main(String[] args) {

int data[] = { 6, 3, 7, 5};

for(int row=0; row<data.length-1; row++) {

for(int col=row+1; col<data.length; col++) {

if(data[row]>data[col]) {  

int temp= data[row];

data[row] = data[col+1];

data[col+1] = temp;

}

}

}

System.out.print("결과 : ");

for(int i=0; i<4; i++) {

System.out.print(data[i] + "\t");

}

}

}



● 버블 정렬



public class BubbleSort {

public static void main(String[] args) throws java.io.IOException {

int data[] = { 6, 3, 7, 5};

for(int row=0; row<data.length-1; row++) {

for(int col=0; col<data.length-1; col++) {

if(data[col]>data[col+1]) { // >는 오름차순  < 내림차순

int temp= data[col];

data[col] = data[col+1];

data[col+1] = temp;

}

}

}

System.out.print("결과 : ");

for(int i=0; i<4; i++) {

System.out.print(data[i] + "\t");

}

}

}