---
title: "选择和插入排序(c++)"
author: "wanran"
date: "2011-05-21T13:45:36Z"
tags: []
categories: ["编程语言"]
slug: "c"
draft: false
lastmod: "2011-05-21T13:45:36Z"
id: 1052899
url: "https://wanran.iteye.com/blog/1052899"
---

插入与选择排序是两种基础的排序算法，复杂度都为O(n^2);

```c++

void selectionSort(int list[], int size) {
    cout<<size<<endl;
    int min;
    int temp;
    for(int i=0; i<size-2; i++) {
        int min = i;
        for(int j=i+1; j<size; j++) {
            if(list[j]<list[min]) min = j;
        }
        if(min!=i) {
            temp = list[i];
            list[i] = list[min];
            list[min] = temp;
        }
    }
}

void insertSort(int list[] , int size) {
    int firstOutOfOrder, location;
    int temp;

    for(firstOutOfOrder=1; firstOutOfOrder<size; firstOutOfOrder++) {
        if(list[firstoutoforder]<list[firstoutoforder-1]) {
            temp = list[firstoutoforder];
            location = firstOutOfOrder;

            do {
                list[location] = list[location-1];
                location--;
            }while(location>0&&list[location-1]>temp);
            list[location] = temp;
        }
    }
}

```