简单排序算法 C++类实现

简单排序算法:

  • 冒泡排序
  • 插入排序
  • 选择排序

.h代码:

//
//  SortClass.h
//  sort and selection
//
//  Created by wasdns on 16/10/8.
//  Copyright © 2016年 wasdns. All rights reserved.
//

#ifndef SortClass_h
#define SortClass_h

class Array {

private:
    int *a;
    int n;
    
public:
    Array(int a = 0):n(a){};
    
    void Initial(int n); //数组初始化
    
    void SelectSort();   //选择排序
    
    void BubbleSort();   //冒泡排序
    
    void InsertSort();   //插入排序
    
    void PrintArray();   //输出数组
};

#endif /* SortClass_h */

.cpp代码:

//
//  Implementation.cpp
//  sort and selection
//
//  Created by wasdns on 16/10/8.
//  Copyright © 2016年 wasdns. All rights reserved.
//

#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include "SortClass.h"
using namespace std;

/*
 * 函数名称:SwapNum
 * 函数参数:整形指针p, 交换位置l,交换位置r
 * 函数目的:交换*(p+l)与*(p+r)
 */
void SwapNum(int* p, int l, int r) {
    
    int t;
    t = *(p + l);
    *(p + l) = *(p + r);
    *(p + r) = t;
}

/*
 * 函数名称:Initial
 * 函数参数:数组元素个数num
 * 函数目的:初始化,并输入数组元素的值
 */
void Array::Initial(int num) {
    
    int i;
    
    n = num;
    
    a = (int*)malloc(num);
    
    for (i = 1; i <= n; i++) {
        cin >> *(a + i);
    }
}

/*
 * 函数名称:PrintArray
 * 函数目的:输出数组中的所有元素
 */
void Array::PrintArray() {
    
    for (int i = 1; i <= n; i++) {
        cout << *(a + i) << " ";
    }
    cout << endl;
}

/*
 * 冒泡排序实现:
 */
void Array::BubbleSort() {
    
    int i, j;
    
    for (i = n; i > 1; i--) {
        for (j = 1; j < i; j++) {
            if (*(a + j) > *(a + j + 1)) {
                SwapNum(a, j, j+1);
            }
        }
    }
}

/*
 * 插入排序实现:
 */
void Array::InsertSort() {
    
    int i, j;
    
    for (i = 2; i <= n; i++) {
        
        int turn = i;
        
        for (j = i - 1; j >= 1; j--) {
            
            if (*(a + j) > *(a + turn)) {
                SwapNum(a, j, turn);
                turn = j;
            }
            else break;
        }
    }
    
}

/*
 * 选择排序实现:
 */
void Array::SelectSort() {
    
    int i, j;
    
    for (i = 1; i <= n; i++) {
        
        int k = i;
        for (j = i + 1; j <= n; j++) {
            if (*(a + j) < *(a + k)) k = j;
        }
        
        if (k != i) SwapNum(a, i, k);
    }
    
}

2016/10/8

原文地址:https://www.cnblogs.com/qq952693358/p/5938771.html