は、ここで私はそれがあなたのためにソートされた配列を返します書い追加クイックソート()関数を使用してコードです。私はそれが好きなので、私はquicksortを選択しましたが、任意のソートアルゴリズムを使用することができます。
クイックソートを動作させるために必要なすべての関数を追加しました。すべての関数プロトタイプをmain()の上に追加しました。また、配列内の要素を、印刷していたのと同じ形式で出力するprint_array関数を追加しました。インクルードファイルの上部に記述が含まれた後
はまた、私はライン
#define VECSIZE 25
を追加しました。あなたは定数として多くの値25を使用していましたので、値を別の数値に変更したい場合は、さまざまな場所で値を変更する必要がありました。今、ベクトルのサイズを変更したい場合は、VECSIZEの値を変更するだけです。
#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);
}
}
正確にはどのような問題がありますか?あなたはどのように並べ替えるか、何、仲間をどのようにポインタを使用するか分からない? – 5208760
['qsort()'](http://www.cplusplus.com/reference/cstdlib/qsort/)をチェックしましたか? – Matthieu