このプログラムは、int配列を入力としてソートしてクイックソートを使ってソートしていますが、このプログラムをchar [] []を入力(文字列配列)としてアルファベット順に並べ替えますか? theresのがちょうど1つの文字列場合、それは動作しますが、私は誰かが、文字列int []からchar [] []へのユーザー入力の変換
//following program sorts an array using quicksort alorithm
#include<iostream.h>
#include<conio.h>
void swap(int *a, int *b) //function to swap elements
{
int t;
t = *a;
*a = *b;
*b = t;
}
int partition(int arr[], int left, int right) //function takes last element as pivot and places all smaller elements on left of pivot and greater elements on right
{
int pivot=arr[right]; //Pivot
int i= (left-1); //index of smaller element
for(int j=left; j<=(right-1); j++)
{
if(arr[j]<=pivot) //if current element is smaller or equal to pivot, theyre swapped
{
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i+1], &arr[right]);
return (i+1);
}
void quicksort(int arr[], int left, int right) //left is starting index, right is last index
{
if(left<right)
{
int index=partition(arr,left,right);
quicksort(arr, left, index-1); //sort elements before and after partition
quicksort(arr, index+1, right);
}
}
void print(int *arr, int size) //function to print elements in array
{
for(int i=0; i<size; i++)
{
cout<<arr[i]<<" ";
}
}
int main()
{
int n; //to store no. of elements in array
char ch; //ch for choice
do{
int *arr=NULL; //dynamic int array
clrscr();
cout<<"\nEnter Number of Elements:";
cin>>n;
cout<<"\nEnter Elements in Array to be sorted:";
for(int i=0; i<n; i++)
{
cout<<"\nEnter "<<i<<"th element:";
cin>>arr[i];
}
quicksort(arr,0,(n-1));
cout<<"\nSorted Array= ";
print(arr,n);
delete arr;
cout<<"\nwanna sort again??(y/n):";
cin>>ch;
}while(ch=='Y'||ch=='y');
return 0;
}
文字列を比較するには、 'strcmp()'などを使用してください。 'int's(ポインタは整数のような単純な型です)を入れ替えるだけで、2つの' char * 'を簡単に入れ替えることができます。ところで、あなたのコンパイラは古代です。少なくともC++ 14に対応したものにアップグレードしてください。 MinGW/GCCとMicrosoftの両方のコンパイラは自由に使用できます。 –
C++では 'char []'配列の代わりに 'std :: string'を使うべきです。 – Barmar
@Barmar、これはC++の古いバージョンです。文字列をサポートしていません。 –