![](/img/trans.png)
[英]Optimizing a bubble sort in C that will decrease the number of swaps needed to sort a list of numbers in ascending order
[英]How to count number of swaps in a bubble sort?
所以我需要我的程序打印输入的值并计算交换次数(不是比较)。 到目前为止,除了交换计数器之外,我的一切都在工作。 我尝试通过使用swap++;
增加swap++;
在我的 if 语句和冒泡排序中,但这不起作用。 有任何想法吗? 这是我的代码。
#include <stdio.h>
int sort(int array[], int count);
int main(void) {
int numArray[100];
int counter, value;
printf("Enter array length \n");
scanf("%d", &counter);
int i = 0;
while(i < counter){
scanf("%d", &numArray[i]);
i++;
}
i = 0;
while(i < counter) {
sort(numArray, counter);
i++;
}
int totalSwaps = sort(numArray, counter);
printf("Swaps: %d\n", totalSwaps);
i = 0;
while(i < counter) {
printf("Values: %d\n", numArray[i]);
i++;
}
return 0;
}
int sort(int array[], int count) {
int i, j, temp;
int swaps = 0;
for(i = 0; i < count-1; ++i) {
for(j=0; j < count-1-i; ++j) {
if(array[j] > array[j+1]) {
temp = array[j+1];
array[j+1] = array[j];
array[j] = temp;
swaps++;
}
}
}
return swaps;
}
你有一个 while 循环来对它进行排序count
。 您只需要运行一次排序函数,除非它第一次没有排序。
#include <stdio.h>
int sort(int array[], int count);
int main(void){
int numArray[100];
int counter;
printf("Enter array length \n");
scanf("%d", &counter);
int i;
for (i = 0; i < counter; i++){
printf("%d. Enter a numner: ", i);
scanf("%d", &numArray[i]);
}
// How many times would you like to sort this array?
// You only need one sort
/*
i = 0;
while(i < counter){
sort(numArray, counter);
i++;
}
*/
int totalSwaps = sort(numArray, counter);
if (totalSwaps == 0) {
printf("The array is already in sorted order\n");
return 0;
}
printf("Swaps: %d\n", totalSwaps);
for (i = 0; i < counter; i++) {
printf("Values: %d\n", numArray[i]);
}
return 0;
}
int sort(int array[], int count){
int i, j, temp;
int swaps = 0;
for(i = 0; i < count-1; ++i){
for(j=0; j<count-1-i; ++j){
if(array[j] > array[j+1]){
temp = array[j+1];
array[j+1] = array[j];
array[j] = temp;
swaps++;
}
}
}
return swaps;
}
按升序排列:
在冒泡排序中,最大的元素向右移动。 因此,当在右侧找到较小的元素时,交换就完成了。
所以要计算一个元素的交换次数,只需计算右侧小于它的元素数。
您已经在设置totalSwaps
的值时对数组进行了排序。
i = 0;
while(i < counter){
sort(numArray, counter); // you're already sorting the array here
i++;
}
int totalSwaps = sort(numArray, counter); --> the array is already sorted!
printf("Swaps: %d\n", totalSwaps);
像@ProfOak 建议的那样摆脱你的 while 循环,你就准备好了。
斯威夫特 4 版本:
func countSwaps(a: [Int]) -> Void {
var result = a
var numberOfSwaps = 0
let length = a.count
for i in 0 ..< length - 1 {
for j in 0 ..< length - 1 - i {
if result[j] > result[j + 1] {
result.swapAt(j, j + 1)
numberOfSwaps += 1
}
}
}
print("Array is sorted in \(numberOfSwaps) swaps.")
print("First Element: \(result.first!)")
print("Last Element: \(result.last!)")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.