2015-09-14 55 views
-1

我有我的泡沫排序程序的麻烦..我已经完成除了我有问题,我的函数调用我的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 
+0

的错误消息是很清楚的。你不明白什么? – juanchopanza

+0

许多问题。 1.“swap”中的参数类型丢失。 2.没有声明'temp'类型。 3.你将整数传递给'swap'。这些都是通过引用传递的,所以在函数退出时,'swap'中所做的任何更改都会丢失。我的猜测是,你实际上想要传递一个指向值的指针,而在'swap'中你需要取消引用这些指针。 – kaylum

+0

'void swap(int * x,int * y){int} temp = * x; * x = * y; * y = temp; }',然后在调用者端'swap(&values [j],&values [j + 1]);' – BLUEPIXY

回答

1

个两个问题我可以在代码中发现..

1)额外分号

void swap(*x, *y){ 
      temp = x; 
      x = y; 
      y = temp; 
     }; //end swap function 
    //^Should not have a semi-colon there 

分号在函数原型的结束,也缺少给您码。其他功能也是如此。

2)变量未定义

temp变量是在未声明swap()。做

int* temp; 

3)的参数类型在swap()功能

swap() funtion更改为

void swap(int* x,int* y) 

4)你传递整数到swap()功能。最好将变量的地址传递给swap(),然后使用它进行交换。就像在评论中由BLUEPIXY建议的那样。

你的功能应该是

void swap(int *x, int *y) 
{ 
    int temp = *x; 
    *x = *y; 
    *y = temp; 
} 

而且,你应该把它作为,

swap(&values[j] , &values[j+1]); 
+0

额外的分号几乎没有关系。还有更糟糕的问题。 – juanchopanza

+0

@juanchopanza但我猜想一些错误是由于那个.. – Haris

+0

我原来有你在第3步建议,但它抱怨我转换整数int *或反之亦然 – Cyrus