📜  Julia 中的字符串排序

📅  最后修改于: 2021-11-25 04:45:18             🧑  作者: Mango

Julia 中的字符串排序意味着现在我们正在对字符串的字符进行排序。在 Julia 中,这可以通过将字符串的每个字符放入单独的数组并对数组进行排序的基本逻辑轻松实现。最后将数组连接在一起以获得排序后的数组。

主要任务如下:

  1. 获取字符串的每个字符并将其放入单独的数组中。
  2. 对获取的字符应用排序算法或不同的排序函数。
  3. 加入字符数组并获取排序后的字符串作为输出。

创建字符串字符数组

为了创建字符串存在的字符数组,Julia 提供了一个预定义的函数collect()。该函数返回数组的形式,如果该字符串传递到这个函数在这里是指字符的元素在我们的例子。

例子

Julia
# Defining a String
str1 = string("julia")
  
# Using the collect function
# to fetch each character of the string
a = collect(str1)


Julia
str1 = string("julia")
  
a = collect(str1)
  
# Applying the sort function
b = sort(a)


Julia
# Joining the sorted characters
join(b)


Julia
str1 =string("julia") 
  
a = collect(str1)
  
# using Quicksort algorithm
sort(a, alg = QuickSort)
  
join(b)


Julia
str1 = string("julia") 
  
a = collect(str1)
  
# using Insertionsort algorithm
b = sort(a, alg = InsertionSort)
  
join(b)


Julia
str1 = string("julia") 
  
a = collect(str1)
  
# using sortperm() function
# returns the sorted indexes 
# of each substring and storing in 'k'
k = sortperm(a)


Julia
str1 = string("julia")
  
a = collect(str1)
  
# sorting in reverse order
c = sort(a, rev = true) 
  
join(c)


字符串排序

Julia 为字符串排序提供了各种方法和预定义函数。这些方法将字符数组作为参数并返回排序后的数组。

方法一:使用sort()函数

这对数组的元素进行排序,可用于对整数、字符等数组进行排序。该函数算法进行排序,时间复杂度为 O(N log N)。在此函数,字符串str1作为参数传递。

朱莉娅

str1 = string("julia")
  
a = collect(str1)
  
# Applying the sort function
b = sort(a)

连接 Array 元素以生成 String

要对字符串进行排序,需要将排序后的数组元素重新连接在一起以形成一个字符串。 Julia 提供了一个预定义的函数join()来连接字符数组并形成其中每个字符的子字符串。存储在b 中的排序字符现在作为参数传入join()函数。

朱莉娅

# Joining the sorted characters
join(b)

将字符串拆分为子字符串

拆分字符串是为了将数组拆分为多个子串,这些子串在数组的帮助下单独排序,并在排序后重新连接。 Julia 提供了一个预定义的函数split()collect()函数的工作方式相同,这意味着它返回字符串的每个字符作为字符串记住

方法二:使用sort(fetchedsubstrings ,alg=)函数

它的工作方式与排序函数类似,但具有更好的时间复杂度。时间复杂度等于所用算法的时间复杂度,该算法在上述函数作为参数传递

使用 Quicksort (Best case Time Compexity= O(n log n) ) 算法

这里从 collect 或 split 返回的数组作为函数和排序算法中的参数传递。 然后使用join()函数连接排序后的子字符串。

朱莉娅

str1 =string("julia") 
  
a = collect(str1)
  
# using Quicksort algorithm
sort(a, alg = QuickSort)
  
join(b)

使用插入排序(最佳情况时间复杂度 = O(n) )算法

这里从收集或分割函数返回的数组传递作为使用在函数与算法一起的参数。然后使用join()函数连接排序后的子字符串。

朱莉娅

str1 = string("julia") 
  
a = collect(str1)
  
# using Insertionsort algorithm
b = sort(a, alg = InsertionSort)
  
join(b)

方法三:使用 sortperm(fetchedsubstrings)函数

此函数返回一个索引列表,通过简单地将获取的子字符串作为参数传递,可以在集合上使用这些索引列表来生成排序的集合。

这里获取的子字符串将作为sortperm(a)函数的参数传递。

朱莉娅

str1 = string("julia") 
  
a = collect(str1)
  
# using sortperm() function
# returns the sorted indexes 
# of each substring and storing in 'k'
k = sortperm(a)

现在我们将使用for 循环遍历子字符串数组,并在子字符串数组中传递存储在k中的索引。  

方法四:使用 sort(fetchedsubstrings, rev = true)函数

此函数将数组按降序排序,因为我们已将rev的默认值更改为true ,这实际上是false。在这里,按降序排序后,我们将使用join()函数连接已排序的子字符串。

朱莉娅

str1 = string("julia")
  
a = collect(str1)
  
# sorting in reverse order
c = sort(a, rev = true) 
  
join(c)