字符串排序算法+快速排序

#include <stdio.h>
#include <stdlib.h>
#include <memory>
#include <vector>
#include<string>

using namespace  std;

void swap(int* a, int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

void quicksort(int* arr,int start,int end)
{
    if (start >= end) return;
    int left = start;
    int right = end;
    int mid = arr[(start + end)/2];
    do 
    {
        while (arr[left] < mid) left++;
        while (arr[right] > mid) right--;
        if (left <= right)
        {
            swap(&arr[left], &arr[right]);
            left++;
            right--;
        }
    } while (left<=right);
    quicksort(arr,start, right);
    quicksort(arr,left,end);
}

void swap_str(char* a, char* b)
{
    static char temp[20];
    memcpy(temp,a,strlen(a));
    memset(a,'\0',strlen(a));
    memcpy(a, b,strlen(b));

    memset(b, '\0', strlen(b));
    memcpy(b,temp,sizeof(temp));

    memset(temp, '\0', 20);
} 

void quicksort_str(char** arr, int start, int end)
{
    if (start >= end) return;
    int left = start;
    int right = end;
    char* mid = arr[(start + end) / 2];
    do
    {
        while (strcmp((const char *)arr[left],(const char *)mid)<0)
            left++;
        while (strcmp((const char*)arr[right], (const char*)mid)>0)
            right--;
        if (left <= right)
        {
            swap_str(arr[left], arr[right]);
            left++;
            right--;
        }
    } while (left <= right);
    quicksort_str(arr, start, right);
    quicksort_str(arr, left, end);
}

int main()
{
    int loop = 0;
    int n = 10;
    int arr[] = { 12,32,34,13,64,234,7,2,5652,34 };
    char str[][20] = {"abc","my","dsaf","asfdsa","adce","adfe","wefc","z","za","abcd"};
    char*  a[10];
    for (loop = 0; loop < 10; loop++)
    {
         a[loop] = &str[loop][0];
} quicksort_str(a,
0,9); for (loop=0; loop <10; loop++) { printf("%s ", a[loop]); } }

 

posted @ 2023-09-28 22:20  百叶集  阅读(17)  评论(0编辑  收藏  举报