冒泡排序整體思路:


排序優化:當一趟冒泡排序完畢之后,并未發生任何交換,此時我們可以直接結束回圈,提高演算法效率;
C語言版:
#include <stdio.h>
void BubbleSort() {
int a[5],i=0,j=0,flag=0,t=0;
for (i = 0; i < 5; i++) //陣列輸入
scanf("%d", &a[i]);
for (i = 0; i < 4; i++) {
flag = 0;
for(j=0; j< 5-i ;j++)
if (a[j - 1] > a[j]) {
t = a[j - 1];
a[j - 1] = a[j];
a[j] = t;
flag = 1; //一旦發生交換,將flag置1
}
if (flag == 0)
break;//說明沒有發生交換,跳出回圈
}
for (i = 0; i < 5; i++)
printf("%d ",a[i]);
}
int main() {
BubbleSort();
return 0;
}
嘗試使用C++寫成排序類,可同時滿足其他型別陣列排序:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Sort {
friend int main(); //友元函式訪問私有變數
friend void test1();
friend void test2();
friend void test3();
template<class T>
void BubbleSort(T* vec,int n) {
int flag = 0;//標記法判斷是否發生 交換
for (int i = n; i > 1; i--)
{//一共i個數進行排序
for (int j = 0; j < i - 1; j++)
{
if (vec[j] > vec[j + 1])
{
swap<T>(vec[j], vec[j + 1]);
flag = 1; //發生交換才將flag置1
}
}
if (flag == 0) //一整趟下來沒發生交換,說明無需繼續排序,跳出回圈
break;
}
}
template<class T>
void swap(T& a, T& b) //交換函式
{
a = a + b;
b = a - b;
a = a - b;
}
template<class T>
void printVec(T* vec, int n) //列印輸出陣列
{
for (int i = 0; i < n; i++)
cout << vec[i] << " ";
}
};
void test1()//測驗整型陣列
{
int a[6] = { 30,20,50,10,60,40 };
int n = sizeof(a) / sizeof(int);
Sort s;
s.BubbleSort<int>(a, n);
s.printVec(a, n);
}
void test2()//測驗字符陣列
{
Sort bubsor;
char c[] = "gfedcba";
int n = strlen(c);
bubsor.BubbleSort<char>(c,n);
bubsor.printVec<char>(c, n);
}
void test3()//測驗浮點陣列
{
double a[6] = { 10.2432,60.8843,40.0921,50.2134,20.1234,10.4216 };
int n = sizeof(a) / sizeof(double);
Sort s;
s.BubbleSort(a, n);
s.printVec(a, n);
}
int main() {
cout << "字符陣列冒泡排序:" << endl;
test2();
cout << endl;
cout << endl << "int陣列冒泡排序:" << endl;
test1();
cout << endl;
cout << endl << "double陣列冒泡排序:" << endl;
test3();
cout << endl;
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/250770.html
標籤:其他
