Data Structure Exercises (Finding and Sorting)

Title requirements:
1. Randomly generate 20,000 numbers, choose two sorting algorithms with different complexity from insertion sort, bubble sort, merge sort, and quick sort, and sort these 20,000 numbers;
2. After sorting, use Binary search, to search for a certain number.
Reference Code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define max 100
#define search_num  999
//冒泡排序 
void sort1(int arr[]){
    
    
	int i,j,temp;
	for(i=0; i<max-1; i++){
    
    
        for(j=0; j<max-1-i; j++){
    
    
            if(arr[j] > arr[j+1]){
    
    
                temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
}

 
 //快速排序
 void Quicksort(int arry[],int L,int R){
    
    
	if(L>=R)
		return;
        
	int left=L,right=R;
	int pivot=arry[left];

	while(left<right){
    
    
		while(left<right && arry[right]>=pivot){
    
    
			right--;
		}
		if(left<right){
    
    
			arry[left]=arry[right];
        }
		while(left<right && arry[left]<=pivot){
    
    
			left++;        
        }
		if(left<right){
    
    
			arry[right]=arry[left];
        }
		if(left>=right){
    
    
			arry[left]=pivot;  
		}
    }
	Quicksort(arry,L,right-1);
	Quicksort(arry,right+1,R);
}

//二分查找法
int search(int arr[],int left,int right,int key){
    
    
	while(left<=right){
    
    
		int mid=(left+right)/2;
		if(key==arr[mid])
			return mid;
		if(key>arr[mid])
			left=mid+1;
        else
			right=mid-1;       
		}		
		return -1;
}

int main() {
    
    
	int arr[max];
	int i=0;
    //以时间为参数,播种种子
    srand((unsigned)time(NULL));
    
    //生成随机数字,装载进数组
	while(i<max){
    
    
		arr[i]=rand();
		i++;
	}
    
   //调用冒泡排序 
	printf("调用冒泡排序:\n");
	sort1(arr);
   
	//调用快速排序 
    //printf("调用快速排序 :\n");
	//Quicksort(arr,0,max-1); 

    //打印排序后的数组
	int m=0;
   	while(m<max){
    
    
		printf("arr[%d]:%d\n",m,arr[m]);
		m++;
	}
		
    //调用二分查找法
	int index=search(arr,0,max-1,search_num);
	printf("经过查找,%d的下标为:%d\n",search_num,index);
        
    system("pause");
	return 0;
}

Running results:
1. Call bubble sort to sort the generated random numbers:
insert image description here
2. Call quick sort to sort the generated random numbers:
insert image description here
3. Binary search: (Find the result, return the index, if not found, return -1)
insert image description here

Guess you like

Origin blog.csdn.net/weixin_46220576/article/details/123094560