1.冒泡法排序
public static void bubbleSort(int[] numbers) {
int temp; // 记录临时中间值
int size = numbers.length; // 数组大小
for (int i = 0; i < size; i++) {
for (int j =0; j < size-i-1; j++) {
if (numbers[j] > numbers[j+1]) { // 交换两数的位置
temp = numbers[j];
numbers[j] = numbers[j+1];
numbers[j+1] = temp;
}
}
}
}
2.快速排序
int main(void)
{
int a[6] = {-2, 1, 0, -985, 4, -93};
int i;
QuickSort(a, 0, 5); //第二个参数表示第一个元素的下标 第三个参数表示最后一个元素的下标
for (i=0; i<6; ++i)
printf("%d ", a[i]);
printf("\n");
return 0;
}
void QuickSort(int * a, int low, int high)
{
int pos;
if (low < high)
{
pos = FindPos(a, low, high);
QuickSort(a, low, pos-1);
QuickSort(a, pos+1, high);
}
}
int FindPos(int * a, int low, int high)
{
int val = a[low];
while (low < high)
{
while (low<high && a[high]>=val)
--high;
a[low] = a[high];
while (low<high && a[low]<=val)
++low;
a[high] = a[low];
}//终止while循环之后low和high一定是相等的
a[low] = val;
return high; //high可以改为low, 但不能改为val 也不能改为a[low] 也不能改为a[high]
}
3.二分法(二分法一定是有序的,即先排序在查找)
public int BinarySearch(int[] array, int T)
{
int low, high, mid;
low = 0;
high = array.Length - 1;
while (low <= high)
{
mid = (low + high) / 2;
if (array[mid] < T)
{
low = mid + 1;
}
else if (array[mid]>T)
{
high = mid - 1;
}
else
{
return mid;
}
}
return -1;
}
4. 单链表反转
定义一个结点类:
public class Node {
private int data; //数据域
private Node next; //指针域
public Node(int data) {
super();
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
遍历反转:
public static Node reverse1(Node head){
if (head==null) {
return head;
}
//上一结点
Node pre=head;
//当前结点
Node cur=head.getNext();
//用于存储下一节点
Node tem;
//cur==null 即尾结点
while(cur!=null){
//下一节点存入临时结点
tem=cur.getNext();
//将当前结点指针指向上一节点
cur.setNext(pre);
//移动指针
pre=cur;
cur=tem;
}
head.setNext(null);
return pre;
}