github.com/benz9527/toy-box/algo@v0.0.0-20240221120937-66c0c6bd5abd/sort/bubble.go (about)

     1  package sort
     2  
     3  func BubbleSort(arr []int) {
     4  	n := len(arr)
     5  	for i := 0; i < n; i++ {
     6  		for j := i + 1; j < n; j++ {
     7  			if arr[i] > arr[j] {
     8  				temp := arr[i]
     9  				arr[i] = arr[j]
    10  				arr[j] = temp
    11  			}
    12  		}
    13  	}
    14  }
    15  
    16  func BubbleSortAcc(arr []int) {
    17  	n := len(arr)
    18  	doSort := false
    19  	for i := 0; i < n; i++ {
    20  		doSort = false
    21  		for j := i + 1; j < n; j++ {
    22  			if arr[i] > arr[j] {
    23  				temp := arr[i]
    24  				arr[i] = arr[j]
    25  				arr[j] = temp
    26  				doSort = true
    27  			}
    28  		}
    29  
    30  		if !doSort {
    31  			continue
    32  		}
    33  	}
    34  }