Ad

This is the real "bubble sort", your implementation similar to "selection sort" =)

Code
Diff
  • package main
    
    import "fmt"
    
    func bubble_sort(dataset []int){
      for i := 1; i <= len(dataset)-1; i++ {
        
          if dataset[i] >= dataset[i-1] { continue }
          
          var y int = dataset[i]
          var j int = i - 1
          
          for {
    	      if j < 0 || dataset[j] <= y { break }
          	dataset[j+1] = dataset[j]
    	      j--
          }
          
          dataset[j+1] = y
      }
    }
    
    
    func main(){
    
      dataset := []int{5, 2, 4, 6, 1, 3, 15, 6, 23645, 23, 462, 2, 2, -12};
    
      fmt.Println(dataset)
    
      bubble_sort(dataset);
    
      fmt.Println(dataset)
    }
    
    • package main
    • import "fmt"
    • func swap(dataset []int, a, b int) {
    • var x int = dataset[a]
    • dataset[a] = dataset[b]
    • dataset[b] = x
    • }
    • func bubble_sort(dataset []int){
    • for i := 0; i <= len(dataset)-1; i++ {
    • for j := len(dataset)-1; j >= i + 1; j-- {
    • if dataset[j] < dataset[j-1] {
    • swap(dataset, j, j - 1)
    • for i := 1; i <= len(dataset)-1; i++ {
    • if dataset[i] >= dataset[i-1] { continue }
    • var y int = dataset[i]
    • var j int = i - 1
    • for {
    • if j < 0 || dataset[j] <= y { break }
    • dataset[j+1] = dataset[j]
    • j--
    • }
    • }
    • dataset[j+1] = y
    • }
    • }
    • func main(){
    • dataset := []int{5, 2, 4, 6, 1, 3};
    • dataset := []int{5, 2, 4, 6, 1, 3, 15, 6, 23645, 23, 462, 2, 2, -12};
    • fmt.Println(dataset)
    • bubble_sort(dataset);
    • fmt.Println(dataset)
    • }

for more efficency you may iterate up to sqrt(n) with additional condition

Code
Diff
  • function getFactors (n) {
      if (n < 1 || ! Number.isInteger(n)) return [];
      
      let divisors = [];
      
      for (let i = 1; i <= Math.sqrt(n); ++i) {
        if (n % i === 0) {
            divisors.push(i);
            if (n / i !== i) divisors.push(n / i);
        }
      }
      
      return divisors;
    }
    • function getFactors (n) {
    • if (n < 1 || ! Number.isInteger(n)) return [];
    • let divisors = [];
    • // Only iterates up to n/2, since no divisor will be greater than that
    • for (let i = 1; i <= n / 2; ++i) {
    • if (n % i) continue;
    • else divisors.push(i);
    • for (let i = 1; i <= Math.sqrt(n); ++i) {
    • if (n % i === 0) {
    • divisors.push(i);
    • if (n / i !== i) divisors.push(n / i);
    • }
    • }
    • // Push the original number n to array
    • return divisors.concat([n]);
    • return divisors;
    • }