1.冒泡排序
思想:兩兩比較,大的放後面,每一回都能得出最大值放在最後,然後開始新一輪。
解決:兩個for循環,第一個用於控制長度,第二個用於比較
時復:O(n*n)
代碼:
class BubbleSort {
public:
int* bubbleSort(int* A, int n) {
// write code here
for(int i=n-1;i>0;i--) //用於存每一次的max
{
for(int j=0;j<i;j++) //兩兩比較
{
if(A[j]>A[j+1])
{
int temp = A[j];
A[j] = A[j+1];
A[j+1] = temp;
}
}
}
return A;
}
};
好久沒寫博客,因爲新接了項目,導致一直沒寫算法,懺悔。
2.選擇排序
思想:每次選出最小值
解決:兩個for循環,第一個用於控制長度,第二個用於比較,需要一個min和key來記錄每次的最小值和位置。
時復:O(n*n)
代碼:
class SelectionSort {
public:
int* selectionSort(int* A, int n) {
// write code here
for(int i=0;i<n;i++) //用於控制每一輪的循環和存放每次找出得min
{
int min=A[i];
int key=i;;
for(int j=i;j<n;j++)
{
if(A[j]<min)
{
min=A[j];
key=j;
}
}
int temp=A[i];
A[i]=A[key];
A[key]=temp;
}
return A;
}
};
2.插入排序
思想:就是不斷地把一個數組中的元素,未排序的元素不斷插入到已成功排序的隊列之中。
解決:用兩個循環,外層控制當前需要排序的元素,內層用於對前幾個有序數字進行比較。
時復:O(n*n)
代碼:
class InsertionSort {
public:
int* insertionSort(int* A, int n) {
// write code here
for(int i=1;i<n;i++)
{
for(int j=i;j>0;j--)
{
if(A[j]<A[j-1])
{
int temp = A[j];
A[j]=A[j-1];
A[j-1]=temp;
}
}
}
return A;
}
};