用起泡法将字符串按ASCII码值从小到大排列
时间: 2023-08-09 22:04:14 浏览: 56
好的,下面是用起泡法实现字符串按ASCII码值从小到大排列的 Python 代码:
```python
def bubble_sort_str(s):
n = len(s)
# 转换为字符数组
arr = list(s)
# 起泡排序
for i in range(n):
for j in range(n-i-1):
if ord(arr[j]) > ord(arr[j+1]):
arr[j], arr[j+1] = arr[j+1], arr[j]
# 转换为字符串
res = ''.join(arr)
return res
```
这个函数接受一个字符串作为参数,返回按ASCII码值从小到大排列后的字符串。具体实现是将字符串转换为字符数组,使用起泡排序算法进行排序,然后再将字符数组转换为字符串。其中,`ord()` 函数可以将字符转换为对应的 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码值从小到大排列的过程,希望对你有所帮助!