본문 바로가기

2학년 1학기/객체지향프로그래밍 I

정렬 과제

package Sort;


public class SortTest {


public static void printAll(int[] prevsort)

{

for( int p_temp=0; p_temp<prevsort.length; p_temp++ )

System.out.print(prevsort[p_temp]);

}

public static void main(String[] args) {

// TODO Auto-generated method stub

int[] prevsort = {8, 7, 6, 4, 2};

int[] aftersort; 

System.out.print("정렬전 : ");

printAll(prevsort);

System.out.println();

System.out.println("버블정렬 : ");

BubbleSort bs = new BubbleSort();

aftersort = bs.printBubble(prevsort);

System.out.print("정렬후 : ");

printAll(aftersort);

System.out.println();

int[] prevsort2 = {8, 7, 6, 4, 2};

System.out.println("선택정렬 : ");

SelectionSort ss = new SelectionSort ();

aftersort = ss.printSelection(prevsort2);

System.out.print("정렬후 : ");

printAll(aftersort);

}

}



package Sort;


public class BubbleSort {

public int[] printBubble(int[] arr)

{

boolean mod=false;

int count=1;

int temp;

for( int i=0; i<arr.length-1; i++ )

{

for( int j=0; j < arr.length-1; j++ )

if( arr[j] > arr[j+1] )

{

temp = arr[j];

arr[j] = arr[j+1];

arr[j+1] = temp;

mod=true;

}

if(mod==true)

{

System.out.print(count+"단계 : ");

SortTest.printAll(arr);

System.out.println();

count++;

mod=false;

}

}

return arr;

}

}



package Sort;

public class SelectionSort {
public int[] printSelection(int[] arr)
{
boolean mod=false;
int count=1;
int temp=0;
int temp_r;
for( int i=0; i<arr.length; i++ )
{
temp = i;
for( int j=i; j < arr.length; j++ )
if( arr[temp] > arr[j] )
{
temp = j;
mod=true;
}
temp_r = arr[temp];
arr[temp] = arr[i];
arr[i] = temp_r;
if(mod==true)
{
System.out.print(count+"단계 : ");
SortTest.printAll(arr);
System.out.println();
count++;
mod=false;
}
}
return arr;
}
}


정렬전 : 87642

버블정렬 : 

1단계 : 76428

2단계 : 64278

3단계 : 42678

4단계 : 24678

정렬후 : 24678

선택정렬 : 

1단계 : 27648

2단계 : 24678

정렬후 : 24678