用C++ Builder实现一组数组的排序与插入操作
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用C++ Builder实现一组数组的排序与插入操作相关的知识,希望对你有一定的参考价值。
//--------------------------------------------------------------------------- #pragma hdrstop #include <tchar.h> #include <iostream> //--------------------------------------------------------------------------- #pragma argsused #define DATATYPE int #define MAX 128 using namespace std; typedef struct { DATATYPE mArray[MAX]; int mlen; }Array; Array myArray; void ReadArray(Array *); void PrintArray(Array *); void SortArray(Array *); void DeleteElem(Array *, int); void InsertElem(Array *, int); int _tmain(int argc, _TCHAR* argv[]) { int deleteelm, insertelem; ReadArray(&myArray); PrintArray(&myArray); SortArray(&myArray); PrintArray(&myArray); cout << "delete:"; cin >> deleteelm; DeleteElem(&myArray, deleteelm); PrintArray(&myArray); cout << "insert:"; cin >> insertelem; InsertElem(&myArray, insertelem); PrintArray(&myArray); system("PAUSE"); return 0; } //--------------------------------------------------------------------------- void ReadArray(Array * pBegin) //输入元素 { cout << "len:"; cin >> pBegin->mlen; for(int i = 0; i < pBegin->mlen; i++) { cout << "[" << i+1 << "] = "; cin >> pBegin->mArray[i]; } } void PrintArray(Array * pBegin) //输出元素 { for(int i = 0; i < pBegin->mlen; i++) { cout << pBegin->mArray[i] << ","; } cout << endl; } void SortArray(Array * pBegin) //元素排序 { for(int i= 1; i < pBegin->mlen; i++){ if(pBegin->mArray[i] < pBegin->mArray[i-1]) { int j= i-1; int x = pBegin->mArray[i]; pBegin->mArray[i] = pBegin->mArray[i-1]; while(x < pBegin->mArray[j]) { pBegin->mArray[j+1] = pBegin->mArray[j]; j--; } pBegin->mArray[j+1] = x; } } } void DeleteElem(Array * pBegin, int elem) //删除元素 { for(int i = 0; i < pBegin->mlen; i++) { if (pBegin->mArray[i] == elem) { for (int j = i; j < pBegin->mlen; j++) { pBegin->mArray[j] = pBegin->mArray[j+1]; } pBegin->mlen--; } } } void InsertElem(Array * pBegin, int elem)//插入元素 { pBegin->mArray[pBegin->mlen] = elem; pBegin->mlen++; SortArray(pBegin); }
以上是关于用C++ Builder实现一组数组的排序与插入操作的主要内容,如果未能解决你的问题,请参考以下文章