给定一个字符串数组arr []。使用Bubble Sort对给定的字符串进行排序,并显示排序后的数组。
在冒泡排序中,每当arr [i]> arr [i + 1]交换两个连续的字符串arr [i]和arr [i + 1]。较大的值下沉到底部,因此称为下沉排序。在每次通过结束时,较小的值将逐渐向上“冒泡”直至顶部,因此称为“冒泡排序”。
经过所有传递之后,我们将按排序顺序获得所有字符串。上述算法的复杂度为O(N 2 )。
让我们看一下代码片段:
C++
// C++ implementation
#include
using namespace std;
#define MAX 100
void sortStrings(char arr[][MAX], int n)
{
char temp[MAX];
// Sorting strings using bubble sort
for (int j=0; j 0)
{
strcpy(temp, arr[j]);
strcpy(arr[j], arr[i]);
strcpy(arr[i], temp);
}
}
}
}
int main()
{
char arr[][MAX] = {"GeeksforGeeks","Quiz","Practice","Gblogs","Coding"};
int n = sizeof(arr)/sizeof(arr[0]);
sortStrings(arr, n);
printf("Strings in sorted order are : ");
for (int i=0; i
Java
// Java implementation
class GFG
{
static int MAX = 100;
public static void sortStrings(String[] arr, int n)
{
String temp;
// Sorting strings using bubble sort
for (int j = 0; j < n - 1; j++)
{
for (int i = j + 1; i < n; i++)
{
if (arr[j].compareTo(arr[i]) > 0)
{
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
}
// Driver code
public static void main(String[] args)
{
String[] arr = { "GeeksforGeeks", "Quiz",
"Practice", "Gblogs", "Coding" };
int n = arr.length;
sortStrings(arr, n);
System.out.println("Strings in sorted order are : ");
for (int i = 0; i < n; i++)
System.out.println("String " + (i + 1) + " is " + arr[i]);
}
}
// This code is contributed by
// sanjeev2552
C#
// C# implementation
using System;
class GFG
{
static int MAX = 100;
public static void sortStrings(String[] arr,
int n)
{
String temp;
// Sorting strings using bubble sort
for (int j = 0; j < n - 1; j++)
{
for (int i = j + 1; i < n; i++)
{
if (arr[j].CompareTo(arr[i]) > 0)
{
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
}
// Driver code
public static void Main(String[] args)
{
String[] arr = {"GeeksforGeeks", "Quiz",
"Practice", "Gblogs", "Coding"};
int n = arr.Length;
sortStrings(arr, n);
Console.WriteLine("Strings in sorted order are : ");
for (int i = 0; i < n; i++)
Console.WriteLine("String " + (i + 1) +
" is " + arr[i]);
}
}
// This code is contributed by Princi Singh
输出:
Strings in sorted order are :
String 1 is Coding
String 2 is Gblogs
String 3 is GeeksforGeeks
String 4 is Practice
String 5 is Quiz