我的問題與將整數陣列按降序排序有關,但我遇到了一個非常具體的問題,想知道是否有辦法在不破壞我也實作的二進制搜索功能的情況下解決它。
我的專案總體上是完美的,但根據我的導師的說法,有一個問題是破壞交易。我將一個 txt 檔案讀入一個陣列并列出它們,然后將它們按降序排序,并具有二進制搜索數字所在索引的功能。我的數字按降序排序并按原樣列印(144、115、 100、89 等)。這很好。這就是我們想要的。但是在讀取索引時,144 被列為 index[19],115 被列為 index[18] 等等。這是不好的。我想保持完全相同的輸出,但最大的數字在 index[0],然后是 index[1],并按這樣的順序排列。
這是我的程式的圖片。
我對如何做到這一點有點困惑。我嘗試了一些事情,但無論我如何進行排序,最高數字都在索引的最高點。
這是我的代碼的相關位。
int binarySearch(int array1[], int p, int r, int num) {
if (p <= r) {
int mid = (p r) / 2;
if (array1[mid] == num)
return mid;
if (array1[mid] > num)
return binarySearch(array1, p, mid - 1, num);
if (array1[mid] < num)
return binarySearch(array1, mid 1, r, num);
}
return -1;
}
int main() {
int array1[20]{}; //The array that stores the numbers.
char letters[15]{}; //The array that stores the characters.
ifstream inputData("input.txt"); //This assumes input.txt is stored in the same folder.
int n = 0; //Counter for the arrays
int num; //This is for the binary search function.
char x{};
// Error checking for making sure the file can open
if (!inputData)
{
cout << "Cannot open file.\n";
return 0;
}
else {
cout << "The unsorted list of integers: \n";
for (int n = 0; n <= 19; n ) {
inputData >> array1[n];
if (inputData.fail()) break;
cout << array1[n] << " ";
}
cout << "\n\nThe sorted list of integers in descending order: \n";
int n = sizeof(array1) / sizeof(array1[n]); //I have also tried replacing this line with just "int n = 20" and it didn't appear to make any real difference.
sort(array1, array1 n);
for (int n = 19; n >= 0; n--)
cout << array1[n] << " ";
//When copy-pasting my code across I might be missing a curly bracket or two, don't worry about that stuff.
cout << "\n \nEnter an integer to search: ";
cin >> num;
int index = binarySearch(array1, 0, n - 1, num);
if (index == -1) {
cout << num << " could not be found. Please restart the program and try another number.";
}
else {
cout << "Integer " << num << " found at index [" << index << "] in the sorted integer array.";
}
我覺得我一定遺漏了一些明顯的東西。請幫忙,因為我無法讓這個陣列正常作業。偶爾我亂七八糟的時候,它也會讓我的二分搜索無法正常作業,而且它什么也檢測不到,所以我需要小心行事。
uj5u.com熱心網友回復:
在代碼中,您使用
sort(array1, array1 n);
這將使用小于<運算子進行排序,該運算子將按升序對其進行排序。
但是當你顯示它時:
for (int n = 19; n >= 0; n--)
cout << array1[n] << " ";
您以相反的順序執行此操作(使其看起來像是按降序排序)。如果您以正確的順序顯示它,0那么19它將以實際排序順序顯示。
要按降序排序,您需要使用std::greater:
std::sort(array1, array1 n, std::greater{})
并以正確的順序顯示:
for (int value : array1)
std::cout << value << ' ';
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/526580.html
標籤:C 数组排序索引二分搜索
下一篇:Pandas按日期時間排序
