2015-02-10 5 views
-2

plz скажите мне ошибку. Выполняется отлично, но в массиве не выполняется никаких операций. Не знаю, почему ...Bubble Сортировка в c

#include<stdio.h> 

void BubbleSort(int a[],int size){ 
    int i,j; 
    for(i=0;i<(size-1);i++){ 
     for(j=0;j<(size-i-1);j++){ 
       if(a[j]>a[j+1]){ 
        int temp=a[j]; 
        a[j]=a[j+1]; 
        a[j]=temp; 
       } 
      } 
    } 
} 
void main(){ 
    int a[]={2,5,8,4,6,7,9,1,3}; 
    int size=9; 
    BubbleSort(a,size); 

    int i; 
    for(i=0;i<size;i++) 
     printf("%d\t",a[i]); 
    printf("\n"); 
} 
+3

линии 7 в вашей функции BubbleSort должен быть 'а [J +1] = temp; ', а не' a [j] = temp; '. – Luminous

ответ

2

неправильные данные подкачка:

int temp=a[j]; 
a[j]=a[j+1]; 
a[j]=temp; //you assign the same data that a[j] held before 

должно быть:

int temp=a[j]; 
a[j]=a[j+1]; 
a[j+1]=temp; 
1
  //the swapping of value should be like this: 
      if(a[j]>a[j+1]){ 
       int temp=a[j]; 
       a[j]=a[j+1]; 
       a[j+1]=temp; 
      } 
Смежные вопросы