用起泡法将字符串按ASCII码值从小到大排列
时间: 2023-08-09 13:04:14 浏览: 51
好的,以下是使用冒泡排序法将字符串按ASCII码值从小到大排列的Python代码示例:
```python
def bubble_sort(s):
n = len(s)
for i in range(n):
for j in range(0, n-i-1):
if ord(s[j]) > ord(s[j+1]):
s[j], s[j+1] = s[j+1], s[j]
return ''.join(s)
s = input("请输入字符串:")
sorted_s = bubble_sort(list(s))
print("按ASCII码值从小到大排序后的字符串为:", sorted_s)
```
在这个示例中,我们首先通过 `input()` 函数获取用户输入的字符串,然后将其转换为列表并传递给 `bubble_sort()` 函数进行排序。在 `bubble_sort()` 函数中,我们使用嵌套的 for 循环来实现冒泡排序,其中外层循环控制比较的轮数,内层循环负责相邻元素的比较和交换。如果相邻元素的ASCII码值大小关系不符合要求,则进行交换。最终,我们将排序后的列表转换为字符串并输出到控制台上。
相关问题
用c++写用起泡法将字符串按ASCII码值从小到大排列
以下是用冒泡排序法将字符串按ASCII码值从小到大排列的C++代码:
```c++
#include <iostream>
#include <string>
using namespace std;
void bubbleSort(string& str) {
int len = str.length();
for (int i = 0; i < len - 1; ++i) {
for (int j = 0; j < len - i - 1; ++j) {
if (str[j] > str[j + 1]) {
swap(str[j], str[j + 1]);
}
}
}
}
int main() {
string str;
cout << "Please enter a string: ";
getline(cin, str);
bubbleSort(str);
cout << "Sorted string: " << str << endl;
return 0;
}
```
在上述代码中,我们首先定义一个名为 `bubbleSort` 的函数,该函数接受一个字符串参数并使用冒泡排序法将其按ASCII码值从小到大排列。然后在 `main` 函数中,我们从用户输入中获取一个字符串,调用 `bubbleSort` 函数对其进行排序,并输出排序后的结果。
使用起泡法和选择法将字符串按ASCII码值从小到大排列
好的,让我来为你解答这个问题。
首先,让我们来看看使用起泡法将字符串按ASCII码值从小到大排列的过程:
```python
def bubble_sort(s):
n = len(s)
for i in range(n):
for j in range(n-i-1):
if ord(s[j]) > ord(s[j+1]):
s[j], s[j+1] = s[j+1], s[j]
return s
s = "hello, world!"
s = list(s)
print(bubble_sort(s))
```
使用选择法将字符串按ASCII码值从小到大排列的过程如下:
```python
def selection_sort(s):
n = len(s)
for i in range(n):
min_idx = i
for j in range(i+1, n):
if ord(s[j]) < ord(s[min_idx]):
min_idx = j
s[i], s[min_idx] = s[min_idx], s[i]
return s
s = "hello, world!"
s = list(s)
print(selection_sort(s))
```
以上就是使用起泡法和选择法将字符串按ASCII码值从小到大排列的过程,希望对你有所帮助!