直接用strcmp()就行了
排序算法很多的,下面有几个C++写的字符串排序函数。
C里面不能直接用 > 、< 那些的比较字符串,将大于(小于)符号换成strcmp()函数就行了。
其实跟C差不多,因为没有用类那些的复杂结构,稍微改改就是C了。
#include
#include
#include
using namespace std;
/*-----------------Insertion Sort----------------------------*/
int InsertionSort(string a_sort[], int length)
{
int i,j;
string key;
ofstream fout;
for(j=1; j
key = a_sort[j];
i=j-1;
while( (i>=0)&&(a_sort[i]>key) )
{
a_sort[i+1]=a_sort[i];
i=i-1;
}
a_sort[i+1]=key;
}
return 1;
}
/*--------------------Quick Sort------------------------------------*/
int Partition(string a[], int p, int r)
{
int i, j;
string x, temp;
x = a[r];
i = p-1;
for(j=p; j
if(a[j]<=x)
{
i = i+1;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
temp = a[i+1];
a[i+1] = a[r];
a[r] = temp;
return i+1;
}
int Randomized_Partition(string a[], int p, int r)
{
int i;
string temp;
i = rand() % (p-r) + p;
temp = a[r];
a[r] = a[i];
a[i] = temp;
return Partition(a, p, r);
}
int QuickSort(string a[], int p, int r)
{
int q;
while(p
q = Randomized_Partition(a, p, r);
QuickSort(a, p, q-1);
p = q+1;
}
return 1;
}
/*---------------------BubbleSort-------------------------------------*/
int BubbleSort(string a_sort[], int length)
{
int i, j;
string temp;
for(i=0; i
for(j=length-1; j>i; j--)
{
if( a_sort[j] < a_sort[j-1] )
{
temp = a_sort[j];
a_sort[j] = a_sort[j-1];
a_sort[j-1] = temp;
}
}
}
return 1;
}
/*----------------------HeapSort--------------------------------------*/
int MaxHeapify(string a[], int i, int HeapSize) //调整为最大堆
{
int l, r, largest;
string temp;
l = 2*i+1;
r = 2*i+2;
if( l
largest = l;
else largest = i;
if( r
largest = r;
if ( largest!=i )
{
temp = a[i];
a[i] = a[largest];
a[largest] = temp;
MaxHeapify(a, largest, HeapSize);
}
return 1;
}
int Build_Max_Heap(string a[], int length ) //建最大堆
{
int i;
int HeapSize;
HeapSize = length;
for( i= length/2-1; i>=0; i-- )
MaxHeapify( a, i, length);
return 1;
}
int HeapSort(string a_sort[], int length) //堆排序
{
int i;
int HeapSize;
HeapSize = length;
string temp;
Build_Max_Heap(a_sort, length);
for(i=length-1; i>1; i--)
{
temp = a_sort[0];
a_sort[0] = a_sort[i];
a_sort[i] = temp;
HeapSize -= 1;
MaxHeapify(a_sort,0,HeapSize);
}
return 1;
}
/*--------------------Merge Sort------------------------------------*/
int Merge (string a[], int p, int q, int r)
{
int n1, n2;
int i, j, k;
static string L[n], R[n];////
n1 = q-p+1;
n2 = r-q;
for(i=0; i
for(j=0; j
L[n1+1] = R[n2+1] = "................";
i=1;
j=1;
for (k=p; k {
if ( L[i] <= R[j])
{
a[k]=L[i];
i += 1;
}
else
{
a[k]=R[j];
j += 1;
}
}
return 1;
}
int MergeSort(string a[], int p, int r)
{
int q=0;
if(p
q=(p+r)/2;
MergeSort(a, p, q);
MergeSort(a, q+1, r);
Merge(a, p, q, r);
}
return 1;
}