다음 MergeSort 클래스가 있으므로 비교 및 스왑 카운터를 구현해야합니다. 내 비교 및 교환 카운터가 올바른 위치에 있는지 누군가 확인해 주시겠습니까?Java MergeSort : 카운터 비교 및 교환
위와 같이 스왑 및 카운터 비교를위한 두 가지 클래스 속성이 있습니다. 정확히 어디에 긍정적이지 않은가? A) swapCount와 compareCount (runSort 메서드 또는 mergeSort 메서드에서)를 초기화하고 B) 병합 메서드에서 정확히 swapCount ++를 배치해야하는 위치입니다. 나는 확실히 compareCount ++가 올바른 위치에 있다고 확신한다.
다음은 코드입니다. 답장을 보내 주신 모든 분들께 미리 감사드립니다!
public class MyMergeSort {
private int swapCount;
private int compareCount;
public void runSort() {
//this.compareCount = 0;
//this.swapCount = 0;
mergeSort(this.sortItems,0,sortItems.length);
}
public void mergeSort(String[] data, int first, int n) {
int n1; // Size of the first half of the array
int n2; // Size of the second half of the array
this.compareCount = 0;
this.swapCount = 0;
if (n > 1) {
// Compute sizes of the two halves
n1 = n/2;
n2 = n - n1;
mergeSort(data, first, n1); // Sort data[first] through data[first+n1-1]
mergeSort(data, first + n1, n2); // Sort data[first+n1] to the end
// Merge the two sorted halves.
merge(data, first, n1, n2);
}
}
private void merge(String[] data, int first, int n1, int n2) {
String[] temp = new String[n1+n2]; // Allocate the temporary array
int copied = 0; // Number of elements copied from data to temp
int copied1 = 0; // Number copied from the first half of data
int copied2 = 0; // Number copied from the second half of data
int i; // Array index to copy from temp back into data
// Merge elements, copying from two halves of data to the temporary array.
while ((copied1 < n1) && (copied2 < n2)) {
compareCount++;
if (data[first + copied1].compareTo(data[first + n1 + copied2]) < 0) {
temp[copied++] = data[first + (copied1++)];
//swapCount++;
}
else {
temp[copied++] = data[first + n1 + (copied2++)];
swapCount++;
}
}
// Copy any remaining entries in the left and right subarrays.
while (copied1 < n1)
temp[copied++] = data[first + (copied1++)];
while (copied2 < n2)
temp[copied++] = data[first + n1 + (copied2++)];
// Copy from temp back to the data array.
for (i = 0; i < n1+n2; i++)
data[first + i] = temp[i];
}
}
** 업데이트 11/28/2017 ** 좋은 소식. 나는 마침내 내가 찾던 그냥 뭐 찾은 것 같아요 :
http://www.cs.carleton.edu/faculty/adalal/teaching/f04/117/notes/nov08/Sort.java
큰 감사를 해당 코드의 저자로!
'runSort'에서 개수를 초기화해야합니다. 'mergeSort'에서 초기화하면 재귀 호출 할 때마다 덮어 씁니다. – teppic
감사합니다. 그리고 믿을만한 출처로 보이는 것에서 올바른 방향으로 나아가게 해줄 뭔가를 발견했다고 생각합니다. http://www.cs.carleton.edu/faculty/adalal/teaching/f04/117/notes/nov08 /Sort.java – 72909903