web developer

[JAVA] 버블정렬(오름차순, 내림차순) 본문

Algorithm

[JAVA] 버블정렬(오름차순, 내림차순)

trueman 2021. 12. 1. 16:03
728x90
728x90
public class Sorting {
	public static void main (String args[]) {
		int data[] = {3, 6, 1, 4, 5, 7, 8, 0, 2};
	      for(int i=0;i<data.length-1;i++) {
	          for(int j=0;j<data.length-1-i;j++){
              	   // 오름차순 (>), 내림차순(<)
	              if(data[j]>data[j+1]) {
	                  int tmp=data[j];    
	                  data[j]=data[j+1];
	                  data[j+1]=tmp;
	              }    
	          }
	      }    
	
		for(int i=0; i<data.length; i++) {
			System.out.print(data[i]);
			if(i+1 != data.length) {
				System.out.print(", ");
			}
		}
	}
}
public class Sorting {
	public static void main (String args[]) {
		int data[] = {3, 6, 1, 4, 5, 7, 8, 0, 2};
		
		for(int i=0; i<data.length; i++) {
			for(int j=i+1; j<data.length; j++) {
				// 오름차순 (>), 내림차순(<)
				if(data[i] > data[j]) {
			        int tmp = data[i];
			        data[i] = data[j];
			        data[j] = tmp;
				}
			}
		}
		for(int i=0; i<data.length; i++) {
			System.out.print(data[i]);
			if(i+1 != data.length) {
				System.out.print(", ");
			}
		}
	}
}
// 0, 1, 2, 3, 4, 5, 6, 7, 8 (오름차순)
// 8, 7, 6, 5, 4, 3, 2, 1, 0 (내림차순)
728x90
728x90