모든 색인을 확인하는 데 문제가 있습니다. j
의 세 번째 인덱스는 건너 뜁니다. i[0]
, j[2]
, i[0]
, j[4]
왜 그렇게하는지 모르겠습니다. 또한, 실제로 번호를 교환하는 데 문제가 있습니다. 아무도 내 오류가 어디 있는지 아십니까?Java 선택 정렬
static void selectionSort(int[] arr) {
final long startTime = System.nanoTime(); // starts timer
System.out.println("Selection Sort");
//************** Code For Sorting *****************//
//*************************************************//
int counter = 0;
int first = 0;
int second = 0;
//int[] sorted = Arrays.copyOf(arr, arr.length); // Copies unsorted array to new array
//Arrays.sort(sorted); // sorts unsorted array for compairison later on
for(int i = 0; i < arr.length-1; i++) // comparing the first index value to the rest of the values in the array
{
int minIndex = i;
for(int j = 1; j < arr.length-1; j++) // representing the next index value to the original and comparing it
{
int nextIndex = j;
if(arr[minIndex] < arr[nextIndex])
{
System.out.println("i: " +i);
System.out.println("j: " +j);
System.out.println("Checking next index");
}
if(arr[minIndex] > arr[nextIndex])
{
System.out.println("i: " +i);
System.out.println("j: " +j);
//counter = j; // getting array index
first = arr[minIndex];
second = arr[nextIndex];
minIndex = second;
arr[minIndex] = second;
System.out.println("first:" + first);
System.out.println("second:" + second);
System.out.println("minIndex:" + minIndex);
System.out.println("arr[minIndex]:" + arr[minIndex]) ;
System.out.println("Possible lowest unsorted value");
}
//Swap here
if(arr[arr.length-1] == arr[j]){
arr[0] = second;
arr[counter] = first;
counter = 0;
//minIndex= i+1;
}
}
for(int k = 0; k < arr.length; k++)
{
System.out.print(arr[k] + ", ");
}
System.out.println();
}
이 [post] (http://javahungry.blogspot.com/2013/06/java-sorting-program-code-selection-sort.html)가 추천할만한 곳이라고 가정 해보십시오. –