我有我的泡沫排序程序的麻煩..我已經完成除了我有問題,我的函數調用我的swap()
函數..然後使用作爲參數輸入...麻煩指數在參數..冒泡排序在c
我已經嘗試了很多不同的方式,下面是我最近的嘗試。
我需要將交換作爲單獨的功能。編輯----------------------------- 隨着你的建議,尤其是哈里斯和BLUEPIXY我的代碼似乎工作..
雖然它有一些錯誤,並說它不能開始(即時通訊假設這與更多的代碼塊,因爲它一直給我的問題)
澄清其系統錯誤不是代碼塊錯誤 沒有更多的錯誤代碼
這裏是我的代碼:
#include <stdio.h>
#define MAX 9
//moved values up here so it would be declared before its used below
int values[] = {7, 3, 9, 4, 6, 1, 2, 8, 5};
//functions
void printValues(){
int i;
printf ("{");
for(i = 0;i < 9;i ++){//small for loop to iterate through each element in array
printf("%d ", values[i]);
}//end for loop
printf("}");
} //end printValues
void swap(int *x, int *y){
int* temp;
*temp = *x;
*x = *y;
*y = *temp;
} //end swap function
void sort(){
int i;
int j;
for (i=0;i<9;i++){ // starts our loop; loops 9 times, one for each int, increments for each loop.
for (j=0;j<9-i-1;j++){//starts at max length minus 1 minus i's current pass
if (values[j] > values[j + 1]){
swap(&values[j] , &values[j+1]);
}//end if statement
}//end secondary for loop
}//end main for loop
} //end sort function
//# list; 9 integers
int main(){
printf("Before: \n");
printValues();
sort();
printf("After: \n");
printValues();
return(0);
} // end main
的錯誤消息是很清楚的。你不明白什麼? – juanchopanza
許多問題。 1.「swap」中的參數類型丟失。 2.沒有聲明'temp'類型。 3.你將整數傳遞給'swap'。這些都是通過引用傳遞的,所以在函數退出時,'swap'中所做的任何更改都會丟失。我的猜測是,你實際上想要傳遞一個指向值的指針,而在'swap'中你需要取消引用這些指針。 – kaylum
'void swap(int * x,int * y){int} temp = * x; * x = * y; * y = temp; }',然後在調用者端'swap(&values [j],&values [j + 1]);' – BLUEPIXY