📜  R编程中排序算法的类型

📅  最后修改于: 2022-05-13 01:54:39.713000             🧑  作者: Mango

R编程中排序算法的类型

在 R 语言中可以通过多种方式对数据进行排序。由数据分析师根据数据结构考虑最合适的方法。在 R 编程语言中有多种算法用于对数据进行排序。下面讨论了不同类型的排序函数。使用数组中 1 到 100 之间的 10 个随机数的样本。我们将讨论以下排序算法:

  • 冒泡排序
  • 插入排序
  • 选择排序
  • 归并排序
  • 快速排序

冒泡排序

在该算法中,如果满足标准,则比较并交换两个相邻元素。在冒泡排序中,在每次迭代中,通过交换元素将最大的元素带到数组的末尾(在增加的情况下),因此该算法的名称是冒泡排序。要详细了解冒泡排序算法,请参阅冒泡排序。

R
# function to sort the array using bubble sort
bubble_sort <- function(x)
{
    # calculate the length of array
    n <- length(x)
             # run loop n-1 times
        for (i in 1 : (n - 1)) {
              # run loop (n-i) times
            for (j in 1 : (n - i)) {
                  # compare elements
                if (x[j] > x[j + 1]) {
                    temp <- x[j]
                      x[j] <- x[j + 1]
                      x[j + 1] <- temp
                }
            }
        }
      x
}
 
# take 10 random numbers between 1 - 100
arr <- sample(1 : 100, 10)
 
# sort the array and store the result
# in sorted_array
sorted_array <- bubble_sort(arr)
 
# print sorted_array
sorted_array


R
# insertion sort function to sort array
insertion_sort <- function(x)
{
      # calculate the length of array
    n <- length(x)
      # outer loop
    for (i in 2 : (n))
    {
          # store first element as key
        key = x[i]
        j   = i - 1
          # compare key with elements for
          # its correct position
        while (j > 0 && x[j] > key)
        {
          x[j + 1] = x[j]
          j = j - 1
        }
      # Place key at its correct position
      x[j + 1] = key
    }
      # return sorted array
    x
}
 
# take sample array
arr <- sample(1 : 100, 10)
 
# call insertion sort function
sorted_arr <- insertion_sort(arr)
 
# print sorted array
sorted_arr


R
# function to sort array using selection sort
selection_sort <- function(x)
{
      # length of array
    n <- length(x)
      for (i in 1 : (n - 1))
    {
          # assume element at i is minimum
        min_index <- i
          for (j in (i + 1) : (n))
        {
              # check if element at j is smaller
              # than element at min_index
            if (x[j] < x[min_index]) {
                  # if yes, update min_index
                min_index = j
            }
        }
          # swap element at i with element at min_index
        temp <- x[i]
          x[i] <- x[min_index]
          x[min_index] <- temp
    }
    x
}
 
# take sample input
arr <- sample(1 : 100, 10)
 
# sort array
sorted_arr <- selection_sort(arr)
 
# print array
sorted_arr


R
# function to merge two sorted arrays
merge <- function(a, b) {
      # create temporary array
    temp <- numeric(length(a) + length(b))
   
      # take two variables which initially points to
      # starting of the sorted sub arrays
      # and j which points to starting of starting
      # of temporary array
    astart <- 1
      bstart <- 1
      j <- 1
    for(j in 1 : length(temp)) {
         # if a[astart] < b[bstart]
        if((astart <= length(a) &&
            a[astart] < b[bstart]) ||
            bstart > length(b)) {
              # insert a[astart] in temp and increment
              # astart pointer to next
            temp[j] <- a[astart]
            astart <- astart + 1
        }
      else {
            temp[j] <- b[bstart]
            bstart <- bstart + 1         
        }
    }
    temp
}
 
# function to sort the array
mergeSort <- function(arr) {
   
      # if length of array is greater than 1,
      # then perform sorting
    if(length(arr) > 1) {
       
          # find mid point through which
          # array need to be divided
        mid <- ceiling(length(arr)/2)
       
          # first part of array will be from 1 to mid
        a <- mergeSort(arr[1:mid])
       
         # second part of array will be
          # from (mid+1) to length(arr)
        b <- mergeSort(arr[(mid+1):length(arr)])
       
          # merge above sorted arrays
        merge(a, b)
    }
  # else just return arr with single element
  else {
        arr
    }
}
 
# take sample input
arr <- sample(1:100, 10)
 
# call mergeSort function
result <- mergeSort(arr)
 
# print result
result


R
# function to sort the values
quickSort <- function(arr) {
   
  # Pick a number at random
  random_index <- sample(seq_along(arr), 1);
  pivot <- arr[random_index]
  arr <- arr[-random_index]
   
  # Create array for left and right values.
  left <- c()
  right <- c()
   
  # Move all smaller and equal values to the
  # left and bigger values to the right.
  # compare element with pivot
  left<-arr[which(arr <= pivot)]
  right<-arr[which(arr > pivot)]
   
  if (length(left) > 1)
  {
    left <- quickSort(left)
  }
  if (length(right) > 1)
  {
    right <- quickSort(right)
  }
   
  # Return the sorted values.
  return(c(left, pivot, right))
}
 
# take sample array
arr <- sample(1:100, 10)
 
# call quickSort function
result <- quickSort(arr)
 
# print result
result



输出:



[1]  2 19 26 68 74 76 80 81 82 91

插入排序

在这个排序算法中,比较排序和未排序的元素,每次迭代后将未排序的元素放在正确的位置。在该算法中,假设第一个元素已排序,第二个元素作为需要排序的关键元素单独存储。然后将键与排序的元素进行比较。如果排序元素大于关键元素,则交换它们的位置,关键元素成为第一个元素。要详细了解插入排序算法,请参阅插入排序。

电阻

# insertion sort function to sort array
insertion_sort <- function(x)
{
      # calculate the length of array
    n <- length(x)
      # outer loop
    for (i in 2 : (n))
    {
          # store first element as key
        key = x[i]
        j   = i - 1
          # compare key with elements for
          # its correct position
        while (j > 0 && x[j] > key)
        {
          x[j + 1] = x[j]
          j = j - 1
        }
      # Place key at its correct position
      x[j + 1] = key
    }
      # return sorted array
    x
}
 
# take sample array
arr <- sample(1 : 100, 10)
 
# call insertion sort function
sorted_arr <- insertion_sort(arr)
 
# print sorted array
sorted_arr


输出:



[1] 10 27 30 41 58 77 80 89 90 85

选择排序

这种排序算法在R语言中被广泛使用。在这里,未排序列表中的最小元素在每次迭代时被推送到列表的开头。要详细了解选择排序算法,请参阅选择排序。

电阻

# function to sort array using selection sort
selection_sort <- function(x)
{
      # length of array
    n <- length(x)
      for (i in 1 : (n - 1))
    {
          # assume element at i is minimum
        min_index <- i
          for (j in (i + 1) : (n))
        {
              # check if element at j is smaller
              # than element at min_index
            if (x[j] < x[min_index]) {
                  # if yes, update min_index
                min_index = j
            }
        }
          # swap element at i with element at min_index
        temp <- x[i]
          x[i] <- x[min_index]
          x[min_index] <- temp
    }
    x
}
 
# take sample input
arr <- sample(1 : 100, 10)
 
# sort array
sorted_arr <- selection_sort(arr)
 
# print array
sorted_arr


输出

[1] 6 16 21 28 31 48 57 73 85 99

归并排序

这是一个分而治之的算法。我们将数组从 mid 分成两部分,对这两个数组进行排序并合并它们。整个过程是递归完成的。要详细了解归并排序算法,请参阅归并排序。



电阻

# function to merge two sorted arrays
merge <- function(a, b) {
      # create temporary array
    temp <- numeric(length(a) + length(b))
   
      # take two variables which initially points to
      # starting of the sorted sub arrays
      # and j which points to starting of starting
      # of temporary array
    astart <- 1
      bstart <- 1
      j <- 1
    for(j in 1 : length(temp)) {
         # if a[astart] < b[bstart]
        if((astart <= length(a) &&
            a[astart] < b[bstart]) ||
            bstart > length(b)) {
              # insert a[astart] in temp and increment
              # astart pointer to next
            temp[j] <- a[astart]
            astart <- astart + 1
        }
      else {
            temp[j] <- b[bstart]
            bstart <- bstart + 1         
        }
    }
    temp
}
 
# function to sort the array
mergeSort <- function(arr) {
   
      # if length of array is greater than 1,
      # then perform sorting
    if(length(arr) > 1) {
       
          # find mid point through which
          # array need to be divided
        mid <- ceiling(length(arr)/2)
       
          # first part of array will be from 1 to mid
        a <- mergeSort(arr[1:mid])
       
         # second part of array will be
          # from (mid+1) to length(arr)
        b <- mergeSort(arr[(mid+1):length(arr)])
       
          # merge above sorted arrays
        merge(a, b)
    }
  # else just return arr with single element
  else {
        arr
    }
}
 
# take sample input
arr <- sample(1:100, 10)
 
# call mergeSort function
result <- mergeSort(arr)
 
# print result
result


输出

[1] 6 8 16 19 21 24 35 38 74 90

快速排序

这是一个分而治之的算法。它选取一个元素作为枢轴并围绕选取的枢轴对给定数组进行分区。枢轴可以是随机的。要详细了解合并排序算法,请参阅快速排序。

电阻

# function to sort the values
quickSort <- function(arr) {
   
  # Pick a number at random
  random_index <- sample(seq_along(arr), 1);
  pivot <- arr[random_index]
  arr <- arr[-random_index]
   
  # Create array for left and right values.
  left <- c()
  right <- c()
   
  # Move all smaller and equal values to the
  # left and bigger values to the right.
  # compare element with pivot
  left<-arr[which(arr <= pivot)]
  right<-arr[which(arr > pivot)]
   
  if (length(left) > 1)
  {
    left <- quickSort(left)
  }
  if (length(right) > 1)
  {
    right <- quickSort(right)
  }
   
  # Return the sorted values.
  return(c(left, pivot, right))
}
 
# take sample array
arr <- sample(1:100, 10)
 
# call quickSort function
result <- quickSort(arr)
 
# print result
result


输出:

[1] 13 18 21 38 70 74 80 83 95 99