Hier ist der Code mit der zusätzlichen quicksort() Funktion schrieb ich, dass für Sie eine sortierte Array zurück. Ich wählte Quicksort, weil ich es mag, aber jeder Sortieralgorithmus könnte verwendet werden.
Ich habe alle relevanten Funktionen hinzugefügt, damit Quicksort funktioniert, und ich habe alle ihre Funktionsprototypen über main() hinzugefügt. Ich habe auch eine print_array-Funktion hinzugefügt, die die Elemente im Array im selben Format druckt, in dem sie gedruckt wurden.
Außerdem habe ich die Linie
#define VECSIZE 25
nachdem die Anweisungen an den Anfang der Datei enthalten. Sie haben den Wert 25 oft als Konstante verwendet. Wenn Sie also den Wert in eine andere Zahl ändern wollten, müssten Sie ihn an vielen verschiedenen Stellen ändern. Wenn Sie jetzt die Größe des Vektors ändern möchten, müssen Sie nur den Wert von VECSIZE ändern.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define VECSIZE 25
/* function prototypes */
void quicksort(double *vector, int low, int high);
int partition(double *vector, int low, int high);
void swap(double *array, int i, int j);
void print_array(double *array, int size);
int main() {
char vect1[VECSIZE];
char *num1;
//First Vector
printf("Enter first Vector seperated by spaces\n");
fgets(vect1, VECSIZE, stdin);
double v1[VECSIZE];
int count1=0;
num1 = strtok(vect1, " ");
while (num1 != NULL)
{
sscanf(num1, "%lf", &v1[count1]);
num1 = strtok(NULL, " ");
count1++;
}
printf("The unsorted vector is: \n");
print_array(v1, count1);
printf("Size of Array= %d\n\n", count1);
quicksort(v1, 0, count1-1); // count1-1 is the index of the last element in the array
printf("The sorted vector is: \n");
print_array(v1, count1);
}
void print_array(double *array, int size){
int i;
for (i = 0; i < size; i++)
printf("%.2f\n", array[i]);
printf("\n");
}
/*
x and y are indices into the array, and the values
at those indexs will be swapped
*/
void swap(double *array, int x, int y) {
int placeholder = array[x];
array[x] = array[y];
array[y] = placeholder;
}
/*
Sorts a single element in the array and returns its
sorted index.
*/
int partition(double *array, int low, int high) {
int i = low-1;
int j = low;
double pivot = array[high];
for (j; j < high; j++) {
if (array[j] <= pivot) {
i++;
swap(array, i, j);
}
}
i++;
swap(array, i, high);
return i;
}
/*
recursively sorts an array by sorting the values in the
array that are left of 'mid' and then sorting the values
that are greater than 'mid'. The brains of this sorting
algorithm is in the partition function.
*/
void quicksort(double *array, int low, int high) {
int mid;
if (low < high) {
mid = partition(array, low, high);
quicksort(array, low, mid-1);
quicksort(array, mid+1, high);
}
}
Was genau ist das Problem? Sie wissen nicht, wie man Zeiger benutzt, wie man sortiert oder was, Bruder? – 5208760
Haben Sie ['qsort()'] (http://www.cplusplus.com/reference/cstdlib/qsort/) überprüft? – Matthieu