我让这个程序把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;
}
答案 0 :(得分:2)
代码中的整数版本需要int *arr = new int[n];
来分配整数数组。
要使用字符串数组执行此操作,请声明char **arr = new char*[n];
并使用strdup
为每个字符串指定char数组。
您应该可以在较旧的编译器中使用标准qsort
,否则请使用此快速排序的修改版本。主要区别在于用if(arr[j]<=pivot){}
if(strcmp(arr[j], pivot) <= 0){}
void swap(char* &a, char* &b)
{
char *t = a;
a = b;
b = t;
}
int partition(char** arr, int lo, int hi)
{
int i = lo - 1;
for(int j = lo; j < hi - 1; j++)
{
if(strcmp(arr[j], arr[hi]) < 0)
{
i++;
swap(arr[i], arr[j]);
}
}
if(strcmp(arr[hi], arr[i + 1]) < 0)
swap(arr[hi], arr[i + 1]);
return i + 1;
}
void quicksort(char** arr, int const lo, int const hi)
{
if(lo < hi)
{
int p = partition(arr, lo, hi);
quicksort(arr, lo, p);
quicksort(arr, p + 1, hi);
}
}
void print(char **arr, int size)
{
for(int i = 0; i<size; i++)
cout << arr[i] << ", ";
cout << "\n";
}
int main()
{
int n;
cout << "Enter Number of Elements: ";
cin >> n;
cout << "Enter Elements in Array to be sorted:\n";
char buf[255];
char **arr = new char*[n];
for(int i = 0; i < n; i++)
{
cout << "Enter " << i << "th element: ";
cin >> buf;
arr[i] = strdup(buf);
}
quicksort(arr, 0, (n - 1));
cout << "Sorted:\n";
print(arr, n);
cout << "\n";
for(int i = 0; i < n; i++)
free(arr[i]); //<=== edit**
delete[]arr;
return 0;
}
编辑1:更改了quicksort
功能
编辑2:更改了清理。必须使用strdup
free