经典排序算法
快排:
static int partition(int[] unsorted, int low, int high)
{
int pivot = unsorted[low];
while (low < high)
{
while (low < high && unsorted[high] > pivot) high--;
unsorted[low] = unsorted[high];
while (low < high && unsorted[low] <= pivot) low++;
unsorted[high] = unsorted[low];
}
unsorted[low] = pivot;
return low;
}
static void quick_sort(int[] unsorted, int low, int high)
{
int loc = 0;
if (low < high)
{
loc = partition(unsorted, low, high);
quick_sort(unsorted, low, loc - 1);
quick_sort(unsorted, loc + 1, high);
}
}
桶排序:
static int[] bucket_sort(int[] unsorted, int maxNumber = 99)
{
int[] sorted = new int[maxNumber + 1];
for (int i = 0; i < unsorted.Length; i++)
{
sorted[unsorted[i]] = unsorted[i];
}
return sorted;
}
冒泡:
static void bubble_sort(int[] unsorted)
{
for (int i = 0; i < unsorted.Length; i++)
{
for (int j = i; j < unsorted.Length; j++)
{
if (unsorted[i] > unsorted[j])
{
int temp = unsorted[i];
unsorted[i] = unsorted[j];
unsorted[j] = temp;
}
}
}
}
选择排序:
static void selection_sort(int[] unsorted)
{
for (int i = 0; i < unsorted.Length; i++)
{
int min = unsorted[i], min_index = i;
for (int j = i; j < unsorted.Length; j++)
{
if (unsorted[j] < min)
{
min = unsorted[j];
min_index = j;
}
}
if (min_index != i)
{
int temp = unsorted[i];
unsorted[i] = unsorted[min_index];
unsorted[min_index] = temp;
}
}
}
插入排序:
static void insertion_sort(int[] unsorted)
{
for (int i = 1; i < unsorted.Length; i++)
{
if (unsorted[i - 1] > unsorted[i])
{
int temp = unsorted[i];
int j = i;
while (j > 0 && unsorted[j - 1] > temp)
{
unsorted[j] = unsorted[j - 1];
j--;
}
unsorted[j] = temp;
}
}
}
归并排序:
- //将有二个有序数列a[first...mid]和a[mid...last]合并。
- void mergearray(int a[], int first, int mid, int last, int temp[])
- {
- int i = first, j = mid + 1;
- int m = mid, n = last;
- int k = 0;
- while (i <= m && j <= n)
- {
- if (a[i] <= a[j])
- temp[k++] = a[i++];
- else
- temp[k++] = a[j++];
- }
- while (i <= m)
- temp[k++] = a[i++];
- while (j <= n)
- temp[k++] = a[j++];
- for (i = 0; i < k; i++)
- a[first + i] = temp[i];
- }
- void mergesort(int a[], int first, int last, int temp[])
- {
- if (first < last)
- {
- int mid = (first + last) / 2;
- mergesort(a, first, mid, temp); //左边有序
- mergesort(a, mid + 1, last, temp); //右边有序
- mergearray(a, first, mid, last, temp); //再将二个有序数列合并
- }
- }
浙公网安备 33010602011771号