一、单链表反转
#include <iostream>
using namespace std;
typedef struct List
{
int a;
struct List* next;
}MyList;
MyList* ReverseList(MyList* head)
{
if(null == head)
return null;
MyList * first = null, * second = null;
while(head)
{
second = head->next;
head->next = first;
first = head;
head = second;
}
return head;
}
参考博客:https://blog.csdn.net/ekaake/article/details/79938245
二、冒泡排序
#include <iostream>
using namespace std;
void swap(int arr[], int a, int b)
{
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
void BubbleSort(int arr[], int n)
{
fot(int j = 0; j < n-1; j++)
{
for(int i = 0; i < n-1-j; i++)
{
if(arr[i] > arr[i+1])
swap(arr, arr[i], arr[i+1]);
}
}
}
int main()
{
int A[] = { 6, 5, 3, 1, 8, 7, 2, 4 }; // 从小到大冒泡排序
int n = sizeof(A) / sizeof(A[0]);
BubbleSort(A, n);
printf("冒泡排序结果:");
for (int i = 0; i < n; i++)
{
printf("%d ", A[i]);
}
printf("\n");
return 0;
}
三、选择排序
#include <iostream> using namespace std; void swap(int arr[], int a, int b) { int temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } void SelectSort(int arr[], int n) { for(int i = 0; i < n-1; i++) { int min = i; for(int j = i+1; j < n; j++) { if (A[j] < A[min]) // 找出未排序序列中的最小值 { min = j; } } if (min != i) { Swap(A, min, i); // 放到已排序序列的末尾,该操作很有可能把稳定性打乱,所以选择排序是不稳定的排序算法 } } } } int main() { int A[] = { 8, 5, 2, 6, 9, 3, 1, 4, 0, 7 }; // 从小到大选择排序 int n = sizeof(A) / sizeof(int); SelectionSort(A, n); printf("选择排序结果:"); for (int i = 0; i < n; i++) { printf("%d ", A[i]); } printf("\n"); return 0; }
四、插入排序
#include <iostream>
using namespace std;
void InsertSort(int arr[], int n)
{
for(int i = 1; i < n; i++)
{
int get = arr[i];
int j = i - 1;
while(j >= 0 && arr[j] > get)
{
arr[j+1] = arr[j];
j--;
}
arr[j+1] = get;
}
}
int main()
{
int A[] = { 6, 5, 3, 1, 8, 7, 2, 4 };// 从小到大插入排序
int n = sizeof(A) / sizeof(int);
InsertionSort(A, n);
printf("插入排序结果:");
for (int i = 0; i < n; i++)
{
printf("%d ", A[i]);
}
printf("\n");
return 0;
}