Quicksort sortiert nicht richtig



  • Um das Programm einfach zu halten, wird quicksort auf 10 arrayelemente reduziert:
    hier der code, würde mich um hilfe freuen.

    #include <stdio.h>
    #include <string.h>
    #include <time.h>
    
    int partition(int* array, int begin, int end){
    
        int x = array[begin];
        int i=begin-1;
        int j=end+1;
        int tmp;
    
       while((i+1)<j){
           i+=1;
           j-=1;
    
          while(array[i]<x && i<=j)
               i+=1;
    
          while(array[j]>x && j>i)
               j-=1;
    
           if(array[i]>array[j]){
               tmp = array[i];
               array[i] = array[j];
               array[j] = tmp;
           }
    
       }
    
       return i;
    }
    
    void quicksort(int* array, int begin, int end){
    
        int q;
        if(begin<end){
            q = partition(array, begin, end);
            quicksort(array, begin, q);
            quicksort(array, q+1, end);
        }
    
    }
    
    int main(void){
    
        int values[10] = { 5 , 3 , 2 , 6 , 1 , 6 , 7 , 2 , 4 , 6 };
        int i;
    
        for(i=0; i<10; i++)
            printf("%2d ", values[i]);
        printf("\nZum sortieren Taste druecken!");
    
        if(getchar())
            quicksort(values, 0, 10);
    
        printf("\n");
    
        for(i=0; i<10; i++)
            printf("%2d ", values[i]);
    
        return 0;
    }
    


  • sorry für doppelpost aber ich weiß .... include <ctime> 😉

    und die bibio wird in dem beispiel nicht benutzt... von daher kann man es ignorieren



  • Quicksort schrieb:

    sorry für doppelpost aber ich weiß .... include <ctime> 😉

    Wenn du mit C arbeitest, ist <time.h> schon richtig 😉

    Zu deinem Problem: Du sortierst die Elemente von array[begin] bis array[end] (also 0 bis 10) inklusive, aber das letzte Element (array[10]) gehört gar nicht mehr zu deinem Array.



  • Hi, danke für die antwort habs zu

    quicksort(values, 0, 9);
    geändert aber da kommt immernoch der fehler:

    das ergebnis lautet

    1 2 2 4 3 6 5 6 6 7

    sry wenn ich grad nicht selber irgendwie vorankommen, nur nach soviel zeit seh ich einfach keinen fehler mehr 😞


Anmelden zum Antworten