我写了一个程序,以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()
或类似的函数。你可以像交换整数一样轻松地交换两个char*
指针(指针是简单类型,就像整数一样)。顺便说一句,你的编译器太古老了。请,请升级到至少支持C++14的版本。MinGW/GCC和Microsoft的编译器都可以免费使用。 - Dúthomhasstd::string
而不是char[]
数组。 - Barmarstd::string
,那么你的编译器是哪个年代的呢? - Quentin