dzungchaos

CTDL&TT: 3 giải thuật sx cơ bản

Jul 5th, 2020
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.65 KB | None | 0 0
  1. void swap(int &a,int &b){
  2.     int temp = a;
  3.     a = b;
  4.     b = temp;
  5. }
  6.  
  7. void selectionSort(int a[], int n){
  8.     int i, j, min;
  9.     for (i = 0; i < n-1; i++) {
  10.         min = i;
  11.         for (j = i+1; j < n; j++){
  12.             if (a[j] < a[min])
  13.                 min = j;
  14.         }
  15.        
  16.         swap(a[i], a[min]);
  17.     }
  18. }
  19.  
  20. void insertionSort(int a[], int size){
  21.     int i, j, key;
  22.    
  23.     for (i = 1; i < size; i++){
  24.         key = a[i];
  25.         j = i;
  26.        
  27.         while((j >= 0) && (a[j-1] > key)){
  28.             a[j] = a[j-1];
  29.             j = j-1;
  30.         }
  31.        
  32.         a[j] = key;
  33.     }
  34. }
  35.  
  36. void bubbleSort(int a[], int size){
  37.     int i,j;
  38.    
  39.     for (i = size-1; i >= 0; i--){
  40.         for (j = 0; j < size; j++){
  41.             if (a[j-1] > a[j])
  42.                 swap(a[j-1], a[j]);
  43.         }
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment