//--------------------------------------------------------------------------- #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); }
原文地址:http://hthinker.blog.51cto.com/5611549/1740768