zoukankan      html  css  js  c++  java
  • 快速排序,冒泡排序

    冒泡:

    #include<iostream>
    #include<stdio.h>
    using namespace std;
    
    void sort(int* arr, int n) {
        int length;
        int i, j;
        int temp;
    
        length = n;
        for (i = 0; i < length; i++) {
            for (j = 0; j < length - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
    
    
    int main() {
        int n;
    
        int i = 0;
    
        int arr[100];
    
        cout << "输入数组元素个数:" << endl;
        
        cin >> n;
    
        cout << "
    输入数组:" << endl;
    
        for (i = 0; i < n; i++) {
    
            cin >> arr[i];
    
        }
    
        cout << "
    输入的数组为:" << endl;
    
        for (i = 0; i < n; i++) {
    
            cout << arr[i] << " , ";
    
        }
    
    
    
        sort(arr, n);
    
    
    
        cout << "
    冒泡结果为:" << endl;
    
        for (i = 0; i < n; i++) {
    
            cout << arr[i] << " , ";
    
        }
    }

    快排:

    #include<iostream>
    
    #include<stdio.h>
    
    #include<stdlib.h>
    
    using namespace std;
    
    
    
    int quicksort(int *arr, int left, int right) {
    
        int mid;
    
    
    
        mid = arr[left];
    
        while (left < right) {
    
            //从右边开始
    
            while(left<right && arr[right]>mid)
    
                right--;
    
            arr[left] = arr[right];
    
    
    
            while(left < right && arr[left] < mid)
    
                left++;
    
            arr[right] = arr[left];
    
        }
    
    
    
        //此时left等于right
    
        arr[left] = mid;
    
        return left;
    
    }
    
    
    
    void sort(int *arr, int left, int right) {
    
        int pivot;
    
    
    
        pivot = arr[left];
    
        if (left < right) {
    
            pivot = quicksort(arr, left, right);  //选出支点
    
            sort(arr, left, pivot - 1);           //负责支点左边的快排
    
            sort(arr, pivot + 1, right);          //负责支点右边的快排
    
        }

    //等到所有排序的left=right了,就会跳出 }
    int main() { int n; int i = 0; int arr[100]; cout << "输入数组元素个数:" << endl; cin >> n; cout << " 输入数组:" << endl; for (i = 0; i < n; i++) { cin >> arr[i]; } cout << " 输入的数组为:" << endl; for (i = 0; i < n; i++) { cout << arr[i] << " , "; } sort(arr, 0, n - 1); cout << "快排结果为:" << endl; for (i = 0; i < n; i++) { cout << arr[i] << " , "; } }
  • 相关阅读:
    clientHeight、offsetHeight、scrollHeight详解
    JavaScript中常见的字符串操作函数及用法
    获取伪元素的属性和改变伪元素的属性
    HTML和CSS实现左侧固定宽度右侧内容可滚动
    gulp常用插件
    gulp入门详细教程
    Javascript 异步实现机制
    JavaScript:彻底理解同步、异步和事件循环(Event Loop)
    chrome调试,打完断点后关于JS的几个控制介绍
    js断点调试心得
  • 原文地址:https://www.cnblogs.com/hikki-station/p/11176025.html
Copyright © 2011-2022 走看看