Browse Source

第二章第一道编程题

DESKTOP-C21C1Q8\tangs 5 years ago
parent
commit
9c057cbafa
2 changed files with 88 additions and 0 deletions
  1. 4 0
      .gitignore
  2. 84 0
      1/1/1/main.cpp

+ 4 - 0
.gitignore

@@ -0,0 +1,4 @@
+.idea
+
+CMakeLists.txt
+cmake-build-debug

+ 84 - 0
1/1/1/main.cpp

@@ -0,0 +1,84 @@
+//
+// Created by tangs on 2018/9/18.
+//
+
+#include <iostream>
+#include <time.h>
+
+using namespace std;
+
+
+struct Digit {
+    int *Ary;
+    int Length;
+
+
+    Digit(int length) {
+        this->Ary = new int[length];
+        for (int i = 0; i < length; i++) {
+            this->Ary[i] = rand();
+        }
+        this->Length= 10;
+    }
+
+    ~Digit() {
+        delete (this->Ary);
+        this->Length = 0;
+    }
+
+    void Print();
+    bool DelMin();
+};
+
+/**
+ * 顺序打印各个元素
+ */
+void Digit::Print() {
+    cout << "NUM: " << this->Length << endl;
+    for (int i = 0; i < this->Length; i++) {
+        cout << this->Ary[i];
+        if (i == this->Length - 1) {
+            cout << endl;
+        } else {
+            cout << "  ";
+        }
+    }
+
+}
+
+/**
+ * 刪除数组中最小元素,并把最后一个元素移到最小值的元素的位置
+ * @return
+ *  false: 有效的删除了一个元素
+ *  ture: 没有元素没删除,或数组为空
+ */
+bool Digit::DelMin() {
+    if (this->Length < 1) {
+        return false;
+    }
+    if (1 == this->Length) {
+        this->Length = 0;
+        return true;
+    }
+    int flag = 0;
+    for (int i = 1; i < this->Length; i++) {
+        if (this->Ary[i] < this->Ary[flag]) {
+            flag = i;
+        }
+    }
+    this->Ary[flag] = this->Ary[this->Length - 1];
+    this->Length--;
+    return true;
+}
+
+int main() {
+    srand((unsigned)time(NULL));
+    Digit digtis(10);
+
+    digtis.Print();
+
+    while (digtis.Length) {
+        digtis.DelMin();
+        digtis.Print();
+    }
+}