快排和冒泡高质量排序
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了快排和冒泡高质量排序相关的知识,希望对你有一定的参考价值。
一、快速排序
(1)排列整数:
#include <stdio.h> #include <stdlib.h> #include <string.h> int com_int(const void *elem1, const void *elem2 ) { return *(int *)elem1 - *(int *)elem2; } int main() { int arr[] = { 1, 3, 5, 7, 2, 4, 6, 8 }; int i = 0; qsort(arr, sizeof(arr) / sizeof(arr[0]), sizeof(arr[0]), com_int); for (i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) { printf("%d ", arr[i]); } printf("\n"); system("pause"); return 0; }
运行结果:
1 2 3 4 5 6 7 8
(2)排列多个字符串:
#include <stdio.h> #include <stdlib.h> #include <string.h> int com_str(const void *elem1, const void *elem2) { return strcmp((char *)*(int *)elem1, (char *)*(int *)elem2); } int main() { char *arr[] = {"bbbb","aaaa","dddd","cccc"}; int i = 0; qsort(arr, sizeof(arr) / sizeof(arr[0]), sizeof(arr[0]), com_str); for (i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) { printf("%s ", arr[i]); } printf("\n"); system("pause"); return 0; }
运行结果:
aaaa bbbb cccc dddd
二、冒泡排字符串
#include<stdio.h> #include<stdlib.h> #include<string.h> void bubble_sort(char*str[], int sz) { int i = 0; int j = 0; for (i = 0; i < sz - 1; i++) { for (j = 0; j < sz - 1 - i; j++) { if (strcmp(str[j], str[j + 1])>0) { char*tmp = NULL; tmp = str[j]; str[j] = str[j + 1]; str[j + 1] = tmp; } } } } int main() { char*str[] = { "hello", "world", "to", "bit", "welcome" };//指针数组 int i = 0; bubble_sort(str, sizeof(str) / sizeof(str[0])); for (i = 0; i < sizeof(str) / sizeof(str[0]); i++) { printf("%s ", str[i]); } printf("\n"); system("pause"); return 0; }
结果:
bit hello to welcome world
优化冒泡(高质量):
#include <stdio.h> #include <stdlib.h> #include <string.h> int com_str(const void *elem1, const void *elem2) { return strcmp((char *)*(int *)elem1, (char *)*(int *)elem2); } void Swap(char *p1, char *p2, size_t sz) { size_t i = 0; for(i = 0; i<sz; i++) { char tmp = *(p1+i); *(p1+i) = *(p2+i); *(p2+i) = tmp; } } void bubble_sort(void *base, size_t num, size_t width, int (*cmp)(const void *elem1, const void *elem2)) { size_t i = 0; size_t j = 0; for(i = 0; i < num-1; i++) { for(j = 0; j < num-1-i; j++) { if(cmp((char *)base+ width*j, (char *)base+width*(j+1)) > 0) { Swap((char *)base+ width*j, (char *)base+width*(j+1), width); } } } } int main() { char *arr[] = {"bbbb","aaaa","dddd","cccc"}; int i = 0; bubble_sort(arr, sizeof(arr)/sizeof(arr[0]), sizeof(arr[0]), com_str); for (i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) { printf("%s ", arr[i]); } printf("\n"); system("pause"); return 0; }
以上是关于快排和冒泡高质量排序的主要内容,如果未能解决你的问题,请参考以下文章