我有一个int* NumList,请使用BubbleSort算法排序,并计算其排序时长
时间: 2023-05-23 11:02:15 浏览: 64
好的,我可以为你编写一个使用BubbleSort算法对NumList进行排序的程序,并计算其排序时长。以下是完整的排序程序代码:
void BubbleSort(int* NumList, int NumCount) {
int temp;
bool swapped;
for (int i = 0; i < NumCount-1; i++) {
swapped = false;
for (int j = 0; j < NumCount-i-1; j++) {
if (NumList[j] > NumList[j+1]) {
// swap
temp = NumList[j];
NumList[j] = NumList[j+1];
NumList[j+1] = temp;
swapped = true;
}
}
// if no elements swapped, then break
if (!swapped) {
break;
}
}
}
int main() {
int* NumList = new int[10] { 5, 1, 9, 3, 7, 4, 6, 8, 2, 0 };
int NumCount = 10;
auto start_time = std::chrono::high_resolution_clock::now();
// Sort the list
BubbleSort(NumList, NumCount);
auto end_time = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time).count();
// Print the sorted list
std::cout << "Sorted list: ";
for (int i = 0; i < NumCount; i++) {
std::cout << NumList[i] << " ";
}
std::cout << std::endl;
std::cout << "Sorting duration: " << duration << " microseconds" << std::endl;
return 0;
}
这个程序会先生成一个长度为10的随机int数组NumList,然后调用BubbleSort函数进行排序,并计算排序时长,最后输出排序后的列表和排序时长。
阅读全文