Algorithm notes two pointers involve algorithms-merge sort/quick sort

Notes on these two sorts:

  • Both need a function to use two pointers to traverse inward from both sides of the array
  • All need a function to express the sort order, such as left and right, where to put merge/partition, the algorithm logic of the writer needs to be clear
  • merge is to sort first, then merge
  • Quicksort is to divide and conquer first, then sort
  • Quicksort is different from dichotomy, dichotomy needs to be traversed to left=right for searching, while quicksort jumps out in time when left==right, and restores the data stored at left at the beginning to ensure that the data on the left is smaller than the data on the right Are greater than the current arr[left]

Merge sort

#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;

void merge(int A[],int L1,int L2,int R1,int R2){
    
    
    int i=L1,j=L2;
    int temp[100005];
    int index=0;
    while(i<=R1&&j<=R2){
    
    
        if(A[i]<=A[j])  temp[index++]=A[i++];
        else    temp[index++]=A[j++];
    }
    while(i<=R1)    temp[index++]=A[i++];
    while(j<=R2)    temp[index++]=A[j++];
    for(int x=0;x<index;x++)
        A[L1+x]=temp[x];
}

void mergesort(int A[],int left,int right){
    
    
    if(left<right){
    
    
        int mid=(left+right)/2;
        mergesort(A,left,mid);
        mergesort(A,mid+1,right);
        merge(A,left,mid+1,mid,right);
    }
}

int main(){
    
    
    int m=0;
    scanf("%d",&m);
    while(m--){
    
    
        int arr[100005]={
    
    0};
        int n=0;
        scanf("%d",&n);
        for(int i=0;i<n;i++){
    
    
            scanf("%d",&arr[i]);
        }
        mergesort(arr,0,n-1);
        for(int i=0;i<n;i++){
    
    
            printf("%d\n",arr[i]);
        }
    }
    return 0;
}

Quick sort

#include <stdio.h>

int partition(int arr[],int left,int right){
    
    
    int temp=arr[left];
    while(left<right){
    
    
        while(arr[right]>temp&&left<right) right--;
        arr[left]=arr[right];//注意要在这里就解决,在最后right会改变
        while(arr[left]<=temp&&left<right) left++;
        arr[right]=arr[left];
    }
    arr[left]=temp;
    //在此处左侧的都比temp小,右侧的都比temp大
    return left;//需要返回下标作为下一次quicksort的位置,类似mid
}

void quicksort(int arr[],int left,int right){
    
    
    if(left<right){
    
    

        int pos=partition(arr,left,right);
        quicksort(arr,left,pos-1);
        quicksort(arr,pos+1,right);
    } 
}

int main(){
    
    
    int arr[5005]={
    
    0};
    int n=0;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
    
    
        scanf("%d",&arr[i]);
    }
    quicksort(arr,0,n-1);
    for(int i=0;i<n;i++){
    
    
        printf("%d\n",arr[i]);
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/Cindy_00/article/details/108566084